What is the scope of variables in JavaScript?

In JavaScript, the scope of a variable refers to the portion of the code where a variable can be accessed or used. There are two types of scopes in JavaScript: global scope and local scope.

  • Global scope: Variables declared outside of any function or block have global scope. They can be accessed from anywhere in the code, including inside functions and blocks.
  • Local scope: Variables declared inside a function or a block have local scope. They can only be accessed within the function or block where they were declared.

A variable that is declared inside a function has local scope, and it will not be accessible outside of the function.

function myFunction() {
  let myLocalVar = "hello";
  // myLocalVar can be accessed within myFunction
}
console.log(myLocalVar); // ReferenceError: myLocalVar is not defined

A variable that is declared in the global scope, will be accessible inside functions

let myGlobalVar = "hello";
function myFunction() {
  console.log(myGlobalVar); // "hello"
}
console.log(myGlobalVar); // "hello"

A variable declared with the var keyword inside a function, will be hoisted to the top of the function and can be accessed before it is declared within the function, but it will only have function scope.

A variable declared with the let or const keyword inside a function or block, will only be accessible within that block, and it can’t be accessed before it is declared. This is called the “temporal dead zone”.

It’s worth noting that if a variable is defined with the same name inside a function, it will shadow any outer variable with the same name.

let x = "global";
function myFunction() {
  let x = "local";
  console.log(x); // "local"
}
console.log(x); // "global"

JavaScript also has block-scoping, which allow to use the let and const to create variables that are only accessible within a given block, like this:

{
  let myBlockVar = "block";
  console.log(myBlockVar); // "block"
}
console.log(myBlockVar); // ReferenceError: myBlockVar is not defined

It’s important to understand the scoping of variables in JavaScript because it can affect how your code behaves and how variables are accessible in different parts of your code.

Leave a Reply