My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

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?