Block statements

Block statements are a series of statements surrounded by curly braces to group them together. A block statement is itself a single statement. When we have more than one statement we want to make conditional with an if, or repeat with a loop, it's simple, we have to use a block statement. But what if we write it first just one statement then refactor it to have two?

var debugMode = false // safe, but ill-advised if (debugMode) console.log('Doing some debugging')

'Doing some debugging' never gets logged, because we aren't in debug mode. But we need some more debugging info.

var debugMode = false // broken if (debugMode) console.log('Doing some debugging') console.log('Wtf this is useless')

Now we always log 'Wtf this is useless', which is probably not what we meant to do, but is very hard to tell as we read the code.

var debugMode = false // much better if (debugMode) { console.log('Doing some debugging') console.log('Wtf this is useless') }

Having the block there to begin with makes it much more likely that it will be refactored correctly later.

I do make an exception for myself in cases where the entire 'if' statement is on a single line. It is nice and concise, though I'm not entirely sure it isn't better to always make it multi line with a block statement.