I have multiple conditions to be checked and executed like below.
if (date == current_date && source === "s3") { table_name = "Table1"; } else if (date == current_date && source !== "s3") { table_name = "Table2"; } else if (date !== current_date && source === "s3") { table_name = "Table3"; } else if (date !== current_date && source !== "s3") { table_name = "Table4"; }
I think using switch statement doesn’t make sense here since we are not evaluating case statement expression against switch expression.
So is it okay to go with multiple if else statements or any better alternative approach?
Advertisement
Answer
Your code is 100% a good option. It is just a bit hard to read. You can pull out common code into variable to make it more readable
var isCurrent = date == current_date; var isS3 = source === "s3"; if (isCurrent && isS3) { table_name = "Table1"; } else if (isCurrent && !isS3) { table_name = "Table2"; } else if (!isCurrent && isS3) { table_name = "Table3"; } else { table_name = "Table4"; }
Other option is to use ternary operators
var isCurrent = date == current_date; var isS3 = source === "s3"; if (isCurrent) { table_name = isS3 ? "Table1" : "Table2"; } else { table_name = isS3 ? "Table3" : "Table4"; }
It could be one big ternary, but it is a bit unreadable
var isCurrent = date == current_date; var isS3 = source === "s3"; table_name = isCurrent ? (isS3 ? "Table1" : "Table2") : (isS3 ? "Table3" : "Table4");