Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Why was block scope not originally implemented in JavaScript?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...