Chaining if else statements and curly braces

if (grade >= 90) {
  console.log("A");
} else if (grade >= 80) {
  console.log("B");
} else if (grade >= 70) {
  console.log("C");
} else if (grade >= 60) {
  console.log("D");
} else {
  console.log("F");
}

The top code is code I pulled of another site (digitalocean.com) & was just using it for syntax purposes. It shows that even the last statement has curly braces around it.

So then in this practice on FCC - why doesn’t the last else statement in this function not require curly braces around the block? I kept getting a syntax error and couldn’t get this code to work without removing the curly braces -

function testSize(num) {

// Only change code below this line

if (num < 5) {

return “Tiny”;

} else if (num < 10) {

return “Small”;

} else if (num < 15) {

return “Medium”;

} else if (num < 20) {

return “Large”;

} else (num >= 20)

return “Huge”;

// Only change code above this line

}

Someone please explain this to me, the only difference I can think of is that the first set of code isn’t in a function while the second one is.

Your issue is not the curly braces. Your issue is this line

} else (num >= 20)

The statement

else (some other test)

doesn’t make much sense because else means ‘all other conditions’. You shouldn’t have a condition here, only a code block.

So then I actually should’ve written this

if (num < 5) {

return “Tiny”;

} else if (num < 10) {

return “Small”;

} else if (num < 15) {

return "Medium";

} else if (num < 20) {

  return "Large";

  } else return "Huge";}

Exactly.
In this case, I would have done

} else
  return "Huge";
}

or better yet

} else {
  return "Huge";
}
}

to match style, but you’ve got the idea.

1 Like

Right! Haha well thanks for helping me out with that. I am going to go and watch like 10 more videos on else if and read about 5 more articles because I thought I understood this whole thing but I am obviously still v confused. x.x

Thanks again!

1 Like

Hey, we all think we know stuff about code until we hit snags and learn even more!

2 Likes