JavaScriptVeryBeiginning

When should I use "else if" instead of "if"?

jyshimmy 2020. 7. 29. 10:39

It's been a month, since I started learning JavaScript. I've been writing many codes using conditional statements. But I'm still confused about exactly under what circumstances, I should use "else if" instead of "if".

 

I got an advice yesterday to write these codes on Google chrome developer page to see the differences, so we'll see how it goes.

 

My guess is that if I'd like to perform 2 actions, or execute twice, when the given 2 conditions return true, I shall use 2 if's, but if I'd like to get only 1 action when given 2 conditions, I shall use if and else if. For, in my understanding, if first if condition passes my function would ends right away with the else if, but with two ifs, my function goes on to the second if condition.

 

My testing code is about whether I'd like to order both drinks and sandwiches.

 

this code tests two conditions separately, thus even if the first condition passes, it still check if the second condition meets as well.

 

when the two arguments are bigger than 0, with else if, as soon as the first if statement passes and executes, the function ends and returns right away, thus even if the second parameter, sandwiches, is 1, which is bigger than 0 and thus the condition meets, in return statement, b is not assigned as the given argument, but is "undefined", because the second if statement was not executed.

is this correct?