Open In App

What is local scope in JavaScript?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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() {
  // Variables declared within this function have local scope
  const localVar = 10;
  console.log(localVar); // Output: 10
}
 
myFunction();
console.log(localVar); // Throws a ReferenceError: localVar is not defined



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads