Am i the only person who is literally clueless?
I guarantee that there are 10 other people out there wondering the same thing but are too chicken to ask. And that’s just on this subject.
Curly braces form a code block, a group of code. In some cases you need them in some you don’t.
First of all, let me redo your code with standard indenting:
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);
That makes it easier to read.
In JS, a function always needs curly braces to make the beginning and the end of the function’s code block.
function testElseIf(val) {
// I am part of this function's definition
// so am I
// so am I
}
// but not me
We also often use them with if
statements, for example,
if (myNum === 1) {
doSomething()
}
Those curly braces tell JS what part of the code is part of the if
- what code is to be run if it is true. You can leave the curly braces off, but then JS will only accept one statement. In this case we only have one statement (calling function doSomething) so we don’t really need the curly braces. These all do the same exact thing:
if (myNum === 1) {
doSomething()
}
if (myNum === 1)
doSomething()
if (myNum === 1) doSomething()
Some people will leave off the curly braces in this case. Some will leave them on.
If you have more than one statement, you need curly braces. This:
if (myNum === 1) {
doSomething1()
doSomething2()
}
would not do the same as this:
if (myNum === 1)
doSomething1()
doSomething2()
In the latter case, doSomething2 would get called every time, regardless of the value in myNum. (Remember that the compiler doesn’t care about indenting.)
In the code that you provided, each if
, else if
, and else
is only doing one thing, so you could leave those curly braces off. I tend to leave them on because I think it is easier to read - but others will disagree.
Semicolons - that’s a controversial subject. They are used in JS to mark the end of a statement. But they aren’t required. A lot of people leave them off. A lot of people insist that they should always be there. On my last job, they insisted on semicolons so that’s what I did. At my current job, they don’t like them so I leave them off. It really doesn’t matter - there are very few situations where they are required. One obvious one is in the for
loop definition.
Don’t worry about it too much.