JavaScript Scope
Scope decides where a variable can be used. A variable made in one place may not be visible in another place.
Global and local scope
let globalVar = "global";
function test() {
let localVar = "local";
console.log(globalVar);
console.log(localVar);
}
test();
console.log(localVar);
global
local
ReferenceError: localVar is not defined
A variable declared outside every function is global, and can be used everywhere. A variable declared inside a function is local, and exists only in that function.
Block scope
A block is the code inside curly braces { }, for example in an if or a loop. let and const stay inside the block. var ignores blocks.
if (true) {
let a = 1;
var b = 2;
}
console.log(b);
console.log(a);
2
ReferenceError: a is not defined
Hoisting
JavaScript moves declarations to the top of their scope before running the code. For var the variable exists, but its value is undefined until the line is reached.
console.log(x);
var x = 5;
console.log(x);
undefined
5
let and const are also hoisted, but you cannot use them before the line where they are declared. This gap is called the temporal dead zone.
console.log(y);
let y = 5;
ReferenceError: Cannot access 'y' before initialization
Function declarations are hoisted completely, so you can call them before they appear in the code.
Nested scope
An inner function can use the variables of its outer function, but not the other way round. This is what makes closures work.
function outer() {
let message = "Hi";
function inner() {
console.log(message); // can see message
}
inner();
}
outer();
Hi
Summary
- Global variables are visible everywhere, local variables only in their function.
letandconstare block scoped,varis function scoped.- Declare variables before you use them.
- Next: JavaScript Data Types.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |