Sign in
Log inSign up

In JavaScript, is it wrong to declare variables within an if-block?

Siddarthan Sarumathi Pandian's photo
Siddarthan Sarumathi Pandian
·Mar 16, 2017

I was recently told not to declare my variables inside an if block.

if (condition) {
    var foo = { bar: 'abcd' };
}
//bunch of code.

However, JavaScript does not have scope blocking. I understand that if the condition is not true, foo is going to be null and doing something like foo.bar later in the code is going to throw me cannot read bar of undefined error.

That being said, is it wrong to do what I did going by ES6 specs?