var vs let vs const in JavaScript

In this article, we explain the var vs let vs const in JavaScript. Also, we will look difference between var, let, and const Keywords in JavaScript. All these three keywords used to create variables in JavaScript. First of all, you must understand the var keyword to grasp the benefits of let and const keywords. So let’s start one by one.

var vs let vs const in JavaScript (Difference)

Var

JavaScript var keyword used to declare a variable, and optionally, we can initialize the value of the variable.

Using var keyword to declare variable are processed first before any codes executed. It’s called hoisting. Moreover, the scope of a variable is only the current execution context. So if you re-declare a variable, then it will not lose its value.

Variable declares globally (outside any function) have global scope. And you can access that variable in function. Whereas variable declares in a function that is only accessed in locally in the function where they are declared. But you can not access a variable outside of the function.

Syntax
var name1 [= value1] [, name2 [= value2] … [, nameN [= valueN];

Here brackets are specified an optional.

Example

In the example, you see var defines both globally and locally.

var xyz = "outside";
function bar() {
    var xyz = "inside";
    console.log(xyz);                     // inside
}
bar();
console.log(xyz);                         // outside

But without var in bar() function, values are updates globally. It is happening because we did not specify the scope for bar().

var xyz = "outside";
function bar() {
  xyz = "inside";
  console.log(xyz);                       // inside
}
bar();
console.log(xyz);                         // inside

Hoisting

Variables declared using var keyword of the top of their scope are always hoisting. Let’s understand here, xyz was declared before logging because of hoisting. When console logging xyz exist but didn’t know what value xyz print. And it will print undefined. Because you didn’t assign anything yet. Later, you assign value to a variable, and then it will log the value of the variable.

var xyz;
console.log(xyz);                       // undefined
xyz = "outside";
console.log(xyz);                       // outside

Function Scope

Variable declared in a function that is limited scope only for that function. You can not access it outside of the function, and it will throw a reference error because xyz exist in bar().

function bar() {
    var xyz = "inside";
    console.log(xyz);                     // inside
}
bar();
console.log(xyz);                        //  ReferenceError: xyz is not defined

Block Scope

Before ES6 JavaScript did not have block Scope. Variables declared with the var keyword can not have block scope.

var xyz = "outside";
if (true) {
  var xyz = "inside";
}
console.log(xyz);                       // inside

xyz is still in the global scope within nearest enclosing {} block. xyz value was updated without our intention. That is the reason ES6 introduce let keyword (var vs let).

Let

Variables declared with the let keyword can have block scoped. Variable declared inside a {} block can’t access from outside the block.

Syntax
let name1 [= value1] [, name2 [= value2] … [, nameN [= valueN];
Example
let xyz = "outside";                      // also you can use var keyword
if (xyz) {
  let xyz = "inside";
}
console.log(xyz);                         // outside

Above example, block scope was separate from the global scope.

let keyword indicate that a variable may be reassigned. Also, indicate that the variable will be used only in the block where it’s defined in. Moreover, the scope is not always the entire containing function. Generally, let keyword we have to use for a counter variable in a loop, or swap value in an algorithm.

Let keyword (Loop Scope)

In this example, let is used to declare the i variable in a loop. Variable i only visible within the loop.

var i = 10;
for (let i = 1; i < 5; i++) {
    console.log(i);             // 1 to 5
}
console.log(i);                 // 10

Const

const keyword restricts to reassigned value to a variable. However, const behavior same as like let variable.

Syntax
const name1 [= value1] [, name2 [= value2] … [, nameN [= valueN];
Example
const xyz = "outside";
xyz = "inside";    // SyntaxError: Identifier 'xyz' has already been declared

Note: const variable can not declare without assigning its value.

const xyz;         // SyntaxError: Missing initializer in const declaration

The behavior of the const, same as like let (block scope).

if (true) {
  const xyz = "inside";
}
console.log(xyz);               // ReferenceError: xyz is not defined
Let and Const are safe?

While we checking let and const keyword does not return correct identifier’s of the variable.

var xyz = "inside";
const ab = "inside";

if (true) {
    let abc = "inside";
    console.log(typeof(abc));          //  string
}
console.log(typeof(xyz));              //  string
console.log(typeof(ab));               //  string

Var vs Let

First, The main difference between var and let keyword, var is follow function scoped while let is follow block scoped. var can be available either in the global scope or function scope. let can be accessible only in enclosing block {} like in a for loop or if condition.

Let vs Const

const keyword is almost the same as let keyword except only one difference. You can’t reassign value to const variable. If you try to reassign value it will throw syntax Error (value has already been declared).

After reading this article you have to understand the var vs let vs const difference. They perform a significant role in JavaScript. You cab share your thoughts here. You can explore here other JavaScript related posts.


2 Responses Leave a Comment

  1. The question is variables declared using let or const can store somewhere in the memory?

    1. SpeedySense Editorial May 30, 2019 at 11:10 PM

      Yes, JavaScript are stored in two places: stack (local context) and heap (store dynamically).

Join the Discussion.