Optionality of curly braces in JavaScript

If there is only one expression in curly brackets in if or else, these curly brackets can be omitted. Let, for example, given the following code with all brackets:

if (test === 0) { console.log('+++'); } else { console.log('---'); }

You can shorten it like this:

if (test === 0) console.log('+++'); else console.log('---');

Или так:

if (test === 0) { console.log('+++'); } else console.log('---');

You can also remove all the brackets, but arrange everything not in one line, but like this:

if (test === 0) console.log('+++'); else console.log('--');

Rewrite the following code in shortened form:

if (test > 0) { console.log('+++'); } else { console.log('---'); }

Rewrite the following code in shortened form:

if (test > 0) { console.log('+++'); }

Comment

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