Skip to main content

Command Palette

Search for a command to run...

Scopes in JavaScript

Understanding scopes in simple words

Published
2 min readView as Markdown
Scopes in JavaScript

What is Scope?

In simple terms Scope is the specific area in code, within this area variables can be accessed.

Types of Scope

  • Global Scope

  • Local Scope

Global Scope

Global scope is the outermost scope in JavaScript. Any variable declared in global scope can be accessed anywhere in the code file.

Example :-

\\ script.js
let name= "vignesh"

Local Scope

Variables that can be accessed only at specific area are called local variables. In other words, all variables other than global variables are local variables in JavaScript.

Example :-

var number1 = 5;
var number2= 5;

function sum(num1, num2) {
    let sum = num1+num2;
    return sume
}
console.log(sum(number1 , number2)); // prints value 10

In the above example sum is a local variable. Any variable declared either in a function or in a block(like a for loop) or inside an if-else / while loops are local variable.

A local scope is divided further into two types,

  • Function Scope

  • Block Scope

Function Scope

A variable declared inside a function stays in the function scope. The variable can be accessed from functions or blocks inside the function(i.e., nested functions) but not from the outside.

Example :-

function sum() {
  const arr = [1, 2, 3];
  let sum = 0; // sum and arr are function scope
  for(let i = 0; i < arr.length; i++) { //i is block scope
    sum = sum + arr[i];
  }
}

Block Scope

Variables declared inside blocks like for loops or inside curly braces { } with let or const are called block-scoped variables.

Example :-

if(number % 2 === 0) {
  let  even = number;
  console.log("Even", even);
} else {
  let odd = number;
  console.log("Odd", odd);
}
console.log("Even", even); //throws error even is not defined
console.log("Odd", odd); //throws error  odd is not defined

Why do we need scope is JS?

Scopes creates execution context for JS engine. when the compiler starts executing a function, all the variables defined inside the function are allocated to memory. Once the function is done executing, the variables in the scope are cleaned from memory.

Because of scoping we can repeat we can repeat the same variable names in different scopes.

Declaring Variables in global scope should be less, as global scope variables will be in the memory until application is closed. Good practice is to use declare variable which are necessary within its scope.