Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

let vs. var vs. const in JavaScript

Programming Bytes

In JavaScript, we can create a variable using three keywords:

  • let
  • var
  • const

What is Scope?

Scope is the accessibility during runtime of variables, functions, or objects in a particular part of your code.

1. Global scope

When we define a variable outside of all document functions, it is in the Global scope and is accessible to all available functions.

var globalVal = 10;

function test() {
  console.log("Printing gloablVal", globalVal);
}

test(); //10 

test JavaScript, in the function in the code above, will check if globalVal is defined. It finds that it is not defined, and then checks in the global scope to find the globalVal. Finally, it prints 10.

The globalVal is stored in the window object, so we can access it using window.globalVal. The variable in the global scope can be accessed and modified in any scope.

2. Function scope

When we define a variable inside a function, we can only access the variable inside the function.

function test(){
 var a = 10;
 console.log("Value of 'a' inside funuction", a);
}
test();
try{
    console.log("Triyng  to access 'a' defined in function ")
    console.log(a); 
}catch(e){
    console.log(e.message); 
}

The visibility of variable a is limited to the test function.

3. Block Scope

When we define a variable inside a block, we can only access the variable inside that block. We can achieve this with let and const.

var has no Block scope.

function test() {
    {
      let a = 10;
      const b = 5;
    }
    
    try{
      console.log("We will get error when we try to access a  b")
      console.log(a, b);// error will be thrown here 
    } catch(e) {
      console.log(e.message);
    }
}
test();

let vs. const

let and const are similar in scope, but they differ in two ways:

  1. We cannot create a const variable without initializing the variable with a value, but we can with let.
let uninitialized; // no error

// correct way to create const 
const MAX = 100;

const val; //Uncaught SyntaxError: Missing initializer in const declaration
  1. We cannot change the value of the const variable; however, we can change the value assigned to a variable created with let.

const is intended to store constant variables.

const MAX = 100;
MAX = 1000; // VM230:1 Uncaught TypeError: Assignment to constant variable

let vs. var

  1. var is function-scoped; whereas, let and const are block-scoped. We cannot create a block-scoped variable using var because blocks had no Lexical Environments in the beginning stages of JavaScript.

Example 1:

function test() {
  {
    let blockScoped = '❌';
    var functionScoped = '✅';
  }
  console.log( "var is Function Scoped ", functionScoped); // '✅' 
  try{
    console.log( "let is bock Scoped ", blockScoped); // '✅'   
  }catch(e){
    console.log(e.message); 
  }
} 
test();
  1. If a variable is created with the var keyword in any block inside a function, then the scope of the variable is the function scope. If it is created in any block outside of the functions, then the scope of the variable is the global scope.

Example 1:

if(true) {
    let blockScoped = '❌';
    var functionScoped = '✅';
}
 console.log( "var is Function Scoped ", functionScoped); // '✅' 
  try{
    console.log( "let is bock Scoped ", blockScoped); // '✅'   
  }catch(e){
    console.log(e.message); 
  }

Example 2:

console.log("using var to create a variable in loop");
for(var i = 0; i < 5; i++){
  // code
}
console.log("value of i defined with var in for loop", i);// 5

console.log("\n------------")
console.log("using let to create a variable in loop");
console.log("\n")

for(let j = 0; j < 5; j++){
  // code
}
try{
  console.log("value of j defined with let in for loop");// 5
  console.log(j);
} catch(e){
  console.log(e.message);
}
  1. Using the var variable before the declaration.

We can access the variable that was created using var before it is declared.

function test() {
  console.log("Accessing a before declaration A = ", a); // undefined
  a = 10;
  console.log("A =", a); // 10
  var a = 5;
  console.log("A = ", a); //5
}
test(); 

This is because the variable that is created with var is created at the beginning of the function execution.

Only the variable is created, and assignments are done once it reaches its assignment statement.

But, we cannot do the same with let or const, or it will throw:


function test() {
  console.log("Trying to access a before declaration");
  console.log(a); // undefined
  let a = 10;
}

test(); // Uncaught ReferenceError: Cannot access 'a' before initialization
  1. The same var variable can be declared multiple times, however, this cannot be done that with let and const.
function test() {
  var a = 10;
  a = 30;
  var a = 100;
  console.log(a); // 100
}
test();

In the code above, JavaScript will create a variable (a) at the start of the function, so any other redeclaration (like var a = 100) will be considered as a = 100.

You can do the same thing using let:

function test() {
    let a = 10;
    a = 30;
    let a = 100;
  
    console.log(a); // Uncaught SyntaxError: Identifier 'a' has already been declared
}

test();

Summary

  • var is used when we need to create a variable inside of a block and want to access the var on the whole function.
  • let is used when we need to create a variable that should be only accessed inside the block.
  • const is used when we need to create a variable that should only be accessed inside the block, and the value of the variable remains unchanged.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring