Javascript scope

Scope determines the accessibility (visibility) of variables.

JavaScript has 3 types of scope:

  • Block scope
  • Function scope
  • Global scope

Block Scope

Before ES6 (2015), JavaScript had only Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:

{ 
  let x = 2;
  }
// x can NOT be used here 

Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.

{
  var x = 2;
}
// x CAN be used here 

Local Scope

Variables declared within a JavaScript function, become LOCAL to the function.

// code here can NOT use carName

function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName 

Local variables have Function Scope:

They can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Function Scope

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

function myFunction() {
var carName = "Volvo"; // block Scope
}

function myFunction() {
let carName = "Volvo"; //block Scope
}

function myFunction() {
const carName = "Volvo"; // block Scope
}

Global Scope

Variables declared Globally (outside any function) have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Variables declared with var, let and const are quite similar when declared outside a block.


var x = 2;       // Global scope

let x = 2;       // Global scope

const x = 2;       // Global scope

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare a global variable carName, even if the value is assigned inside a function.

myFunction();

// code here can use carName

function myFunction() {
  carName = "Volvo";
} 

JavaScript let Vs var

let doesn’t allow to redeclare Variables

1. A variable declared with var can be redeclared again. For example,

var a = 5; // 5
var a = 3; // 3

A variable declared with let cannot be redeclared within the same block or same scope. For example,

let a = 5;
let a = 3; // error 

output
Uncaught SyntaxError: Identifier 'a' has already been declared

References:

https://wordpress.com/post/arokiyakithiyon.wordpress.com/864

https://www.w3schools.com/js/js_scope.asp

Leave a comment

Design a site like this with WordPress.com
Get started