What is local scope in JavaScript?
Last Updated :
14 Feb, 2024
In JavaScript, local scope refers to the scope of variables or identifiers defined within a specific block of code, typically within a function or a block statement (denoted by curly braces {}
). Variables declared within a local scope are only accessible within that scope and are not visible to code outside of it.
Example: Here, the variable localVar
is declared within the myFunction()
function. It has local scope, meaning it is accessible only within the function where it is declared. Attempting to access localVar
outside of the myFunction()
function will result in a ReferenceError
, indicating that the variable is not defined in the global scope.
Javascript
function myFunction() {
const localVar = 10;
console.log(localVar);
}
myFunction();
console.log(localVar);
|
Share your thoughts in the comments
Please Login to comment...