Basic JavaScript: Introducing Else If Statements why to do?

Tell us what’s happening:

I did the else/if statements the same way as shown in the example. But it didn’t work, can someone help, and explain the statements too, and like how they can be used in real projects?

Your code so far


function testElseIf(val) {
if (val > 10) {
  return "Greater than 10";
} else if (val < 5) {
   return "Smaller than 5";
} else {
  return "Between 5 and 15"
}
testElseIf(7);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Introducing Else If Statements

Link to the challenge:

You have missing closing bracket and haven’t changed text of the last case.

For the usage, it isn’t really anything more than the challenge description says already. If there are more conditions than just yes and no then if/else if/else can be used.

First is checked condition by the if, if it’s true then code in that section is executed, and other statements (else if/else) are later ignored. If it’s false then else if statement is checked. If it’s true then code in that section is executed, and else is later ignored. Finally if all previous conditions were false then code by the else is executed.

Keep in mind that else if and else are not required. There can also be multiple else if statements.

For the understanding it might be helpful if you’d try to define by your own what is really happening here and why.

1 Like

So if one condition is not true for example in (ten < 5), it will be go down the list to else if and if this condition is condition is true it will output a certain result like else if(ten > 5), otherwise it will keep going down the list of else if statements to find a true condition, or finally reach the else statement and give a default output right?

Yes, conditions are checked one after one, from top to bottom, until one true is found. If all conditions are false and there’s else that part of code will be executed.