mricci mricci - 7 months ago 15
Javascript Question

Why was block scope not originally implemented in JavaScript?

I have read, and discovered through my own experience, that JavaScript doesn't have block scope. Assuming that the language was designed this way for a reason, what is that reason?

I've looked around on Google and on here, but the posts I have found just reiterate that JS has function scope and not block scope, without explaining why. I'm curious to know why this is actually the case.

Answer

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 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 declared variables are hoisted to the beginning of the enclosing block.
Redeclaration of the same variable in the same block scope raises a TypeError.