I have read, and discovered through my own experience, that JavaScript doesn't have a block scope. Assuming that the language was designed this way for a reason, can you explain to me what is that reason?
I've looked around on Google and here, but the posts I have found just reiterate that JS has a function scope and not block scope, without explaining why. I'm curious to know why this is actually the case.
Variables declared with the var keyword can NOT have block scope. Variables declared inside a { } block can be accessed from outside the block.
The Javascript global scope is the context where everything in a Javascript program executes by default. This scope includes all variables, objects, and references that are not contained within a customized scope defined by a programmer. Global scope is the entire Javascript execution environment.
The main difference between the local scope and block scope is that the block statements (e.g. if conditions or for loops), don't create a new scope. So the var keyword will not have an effect, because the variables are still in the same scope. ES6 introduced block scope by using the let and const keywords.
The block scope restricts a variable's access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block.
Converting my comment to answer
Choice of the creator: I tweeted Brendan and got the following answer:
@mplungjan 10 days did not leave time for block scope. Also many "scripting languages" of that mid-90s era had few scopes & grew more later.
That said, here are some relevant points:
Important: JavaScript prior to ECMAScript2015 (6th edition) does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.
we can artificially introduce scopes by creating new functions and immediately invoking them
let
and const
declared variables are hoisted but they are not initialized to undefined
in the same way var
is. Hence, referencing a let
or const
declared variable before its value is assigned raises a ReferenceError.
Redeclaration of the same variable in the same block scope raises a SyntaxError.
New answer as of 2015. ES6 does have block scope for variable definitions with the let
and const
keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With