Careeroza
Scope
What is Scope?
Scope decides where a variable can be used. JavaScript has global scope, function scope and block scope (inside { } for let/const).
Block and Function Scope
Example
const app = "Careeroza"; // global
function show() {
const local = "inside function"; // function scope
if (true) {
let block = "inside block"; // block scope
var fnScoped = "var ignores blocks";
console.log(app, local, block);
}
console.log(fnScoped);
console.log(typeof block); // not visible here
}
show();Output
Careeroza inside function inside block var ignores blocks undefined
Lexical Scope and Shadowing
Example
Inner functions can read variables of outer functions (lexical scope). A variable with the same name in an inner scope shadows the outer one:
const level = "global";
function outer() {
const level = "outer";
function inner() {
console.log(level); // finds the nearest one
}
inner();
}
outer();
console.log(level);Output
outer global