Scope determines where variables can be accessed or used in a JavaScript program. It defines the visibility and lifetime of variables and functions.
In JavaScript, scope controls where a variable is available and where it is not.
Variables declared outside of any function or block are in the global scope. They can be accessed from anywhere in the program.
let myGlobal = 10; // Global variable
const myFunc = () => {
oopsGlobal = 5; // Not using var, let, or const makes the variable global
};
const myFuncTwo = () => {
let myOutput = "";
if (typeof myGlobal !== "undefined") {
myOutput += `myGlobal: ${myGlobal}\n`; // myGlobal: 10
}
if (typeof oopsGlobal !== "undefined") {
myOutput += `oopsGlobal: ${oopsGlobal}`; // oopsGlobal: 5
}
console.log(myOutput);
};
myFunc();
myFuncTwo();Note: In strict mode, assigning a variable without
var,let, orconstthrows an error.
Strict mode helps you catch common coding mistakes and unsafe actions early by turning them into errors. You can enable strict mode by adding
"use strict"at the top of a JavaScript file or at the beginning of a function.
Variables declared inside a function are function-scoped and can only be accessed within that function.
const myFunc = () => {
var myVar = 5;
console.log(myVar); // 5
};
console.log(myVar); // ReferenceError: myVar is not definedNote: Variables declared with
varfollow function scope, not block scope.
Variables declared using let and const inside a block {} are block-scoped. They are only accessible within that block.
if (true) {
let age = 25;
console.log(age); // 25
}
console.log(age); // ReferenceErrorLexical scope means that inner functions can access variables from their outer scope. Scope is determined by where the code is written, not where it is executed.
const outer = () => {
let count = 10;
function inner() {
console.log(count);
}
inner();
};
outer(); // 10Global vs Local Scope
When the same variable name is used in both global and local scope, the local scope variable takes precedence over the global variable.
let value = 10;
if (true) {
let value = 20; // Takes precedence over global scope
console.log(value); // 20
}
console.log(value); // 10