In JavaScript, there is no concept of block-level scope. Variables defined in block-level statements are actually created in the containing function rather than in the statement. You can place the variable declaration at the top of the function body instead of placing the declaration close to where the variable is used.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Javascript does not have the concept of block-level scope. This means that variables defined in a block-level statement are actually created in the containing function rather than in the statement.
Code segment 1:
var scope="global"; function f(){ console.log(scope); var scope="local" console.log(scope); } f();
What will be output?
Answer: undefined local
Code segment 2:
var scope="global"; function f(){ var scope; console.log(scope); scope="local" console.log(scope); } f();
What will be output?
Answer: undefined local
Code segment 3:
var scope="global"; function f(){ console.log(scope); } f();
What will be output?
Answer: global
Through the above three examples, the following explains the sentence "JavaScript does not have block-level scope, but has function scope".
In JavaScript, due to the characteristics of function scope, code segment 1 and code segment 2 are equivalent, and local variables are defined in the entire function body,
That is Say, the local variable scope in the function body of code segment 1 covers the global variable with the same name, and only when the program executes the var statement, the local variable scope will be truly
assigned. Therefore, the above process is equivalent to: "advancing" the variable declaration within the function to the top of the function body, while leaving the variable initialization at the original position: that is, code segment 2.
In a programming language with block-level scope, it is generally good programming to keep variable declarations and code using variables as close to each other as possible in a small scope
Habit. Because JavaScript does not have block-level scoping, some programmers intentionally place variable declarations at the top of function bodies instead of placing declarations close to where the variables are used. This approach
makes their source code very clearly reflect the variable scope of knowledge.
Related recommendations: javascript learning tutorial
The above is the detailed content of Does javascript have block level scope?. For more information, please follow other related articles on the PHP Chinese website!