JS Curly Braces?

Could someone please explain why I need to close my code with a double closed curly brace? I had everything else written out find and couldn’t work out why it wasn’t working. turned out I was missing a brace. thanks in advance. (I did try googling but not to sure how to word it!).

  **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 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/89.0.4389.105 Safari/537.36.

Challenge: Introducing Else If Statements

Link to the challenge:

If you indent your code, you would see why.

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

The second to last one is for the else statement and the last one closes the function.

1 Like

Ah of course, makes much more sense now. Thanks randell.

I didn’t realise my indentation was incorrect because my code was still passing. Will watch out for it next time.

Yeah, get in the habit of indenting and formatting as you go. Especially as your programs get large, it will save you mountains of headaches. Eventually, when you’re working in the “real world” you’ll be in an editor where you can have a linter or prettier operating so it will catch things like this. It can be hard enough to read the hierarchy of code in some cases even with good formatting - with bad formatting it just gets unnecessarily difficult.

1 Like

Just an FYI. The fCC editor does have a formatter as well.

On Windows, it is Shift + Alt + F or you can do F1 and search for format.

Edit: I should maybe point out that the default formatter will not do a great job of formatting your code. But it’s better than nothing.

1 Like

Thanks Las,

I didn’t know that the editor had a built in formatter. I will give give it a go!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.