You should have closing and opening curly braces for each if else code block

Tell us what’s happening:
Hi, I tried this code for the given challenge. I hope my code is correct but the console says “each ‘Else if’ statement should have opening and closing braces”. What does it mean? Thank you in advance!

My code


function testElseIf(val) {
if (val > 10) {
  return "Greater than 10";
}

else if (val < 5) {
  return "Smaller than 5";
}
else if(val >= 5 && val <= 10){
  return "Between 5 and 10";
}
}

testElseIf(7);

Your browser information:

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

Challenge: Introducing Else If Statements

Link to the challenge:

Hello and welcome to the freeCodeCamp community~!

Double check the example provided in that challenge. The flow is if=>else if=>else. There’s a difference in your flow that is causing the tests to fail.

Thanks for your reply. Yes I checked my code with else statement instead of the else if. It worked. I would like to understand better what difference that else if statement make from the else statement?

when theif statement condition is false the code inside the block will not be executed and if there is not an else statement the execution flow continue after the if block statement. With an else statement you delcare an alternative block to be executed when the if block statement is not executed.
else if statement is when you have multiple if conditions to address. So instead of using if statement for each condition you chain them with else if statements.

2 Likes

Hi @praveenmessi!

I found a great example from this article that illustrates the difference between if, else if and else.

if (condition a) {
    // code that will execute if condition a is true
} else if (condition b) {
    // code that will execute if condition b is true
} else if (condition c) {
    // code that will execute if condition c is true
} else {
    // code that will execute if all above conditions are false
}

Hope that helps!

2 Likes