Problem with optionality of curly braces in if-else

While JavaScript allows the curly braces shorthand shown above, I generally don't recommend doing so, as it's a breeding ground for subtle bugs. For example, let's have the following code:

let test = 3; if (test > 0) console.log(test);

Let now we decide if the condition is met, also display a second message with the text '+++':

let test = 3; if (test > 0) console.log(test); console.log('+++');

However, without curly braces, only the first message is found inside the condition. There is the first line will work under the right condition, and the second - always.

In fact, our code is equivalent to this one:

let test = 3; if (test > 0) { console.log(test); } console.log('+++'); // this line is outside the condition

But we would like such a code:

let test = 3; if (test > 0) { console.log(test); console.log('+++'); // this line is inside the condition }

That is why it is always recommended to put curly braces in order not to fall into this kind of error.

enru