DEV Community

Cover image for The only blog needed to understand var, let and const
jayakrishnan TN
jayakrishnan TN

Posted on • Edited on

The only blog needed to understand var, let and const

Common thing that all javascript programmers search on the web more than once in your career!!!am I right?

It's pretty cool to understand the javascript variable declaration before the era of big gun ES6! The one and only one king - var keyword. On introducing ES6 we have another couple of keywords to implement the variable declaration- let and const.

The best way to understand these keywords by comparing them based on 3 features.
1. Scope of variable
2. Redeclaration
3. Hoisting

Scope of variable

When we declare a variable in JS, the lifetime of the variable in our code is defined as the scope of the variable.

using var keyword

The variable created with var keyword has a scope of current execution context. That means, if the variable is declared outside of all the functions and block of codes, it's scope is global otherwise local to the function or block of codes.

The one important thing is that if the scope of the variable is global it can be accessed with the window object(only in the case of var keyword!).

//  Global Scope
 var varVariable = "John Doe";
 console.log(varVariable);  // Output: "John Doe"
 console.log(window.varVariable);  //  Output:  "John Doe" 
//  Local Scope to the function
function() {
  var varVariable = "John Doe"; 
  console.log(varVariable);  // Output: "John Doe"
}
 console.log(varVariable);  // Output: undefined
 console.log(window.varVariable);  //  Output:  undefined

using let keyword

The let keyword variables have only blocked scope in code execution. That means if a variable declared with let outside of all the functions and block of codes, it's scope is limited to the end of the execution of the code. Otherwise scope is limited to the block or function in which the variable is declared.

Are you confused about the above paragraph? both the var and let keywords are similar when declaring outside of all functions? Maybe you are confused!!

If your answer is a YES, then go to the Hoisting section of this article and read about the let keyword. Then you get a better understanding of the difference. The let and var keyword are almost similar...

//  Variable scope is available to the end of the execution of the code.
 let letVariable = "John Doe";
 console.log(letVariable);  // Output: "John Doe"
 console.log(window.letVariable);  //  Output:  undefined 
//  Block Scope to the function
function() {
  let letVariable = "John Doe"; 
  console.log(letVariable);  // Output: "John Doe"
}
 console.log(letVariable);  // Output: undefined
 console.log(window.letVariable);  //  Output:  undefined

using const keyword

const is a new one for declaring immutable variables in Javascript. that means variable that doesn't change their value when the code execution progress through line by line.

Similar to let keyword, const also have blocked scope.

//  Variable scope is available to the end of the execution of the code.
 const constVariable = "John Doe";
 console.log(constVariable);  // Output: "John Doe"
 console.log(window.constVariable);  //  Output:  undefined 
//  Block Scope to the function
function() {
  const constVariable = "John Doe"; 
  console.log(constVariable);  // Output: "John Doe"
}
 console.log(constVariable);  // Output: undefined
 console.log(window.constVariable);  //  Output:  undefined

Redeclaration

Redeclaring a variable during the lifetime of the variable is possible in javascript.

using var keyword

Redeclaration of a var variable in the same scope is possible. It doesn't throw any error. But the value of the variable is updated as the execution progress. This is not a good method. It will lead to unexpected results in the code execution.

//  Redeclaration in same scope
 var myName= "John Doe";
 console.log(myName);  // Output: "John Doe"
 ...
 ...
 var myName= "jkjaikrishna";
 console.log(myName);  //  Output:  "jkjaikrishna"
//  Redeclaration in different scope
 var myName= "John Doe";
 console.log(myName);  // Output: "John Doe";
 ...
 ...
 function sampleFunction() {
     var myName = "Sam Cooper";
     console.log(myName);  //Output: "Sam Cooper"
 }
 ...
 ...
 sampleFunction();
 ...
 ...
 var myName= "jkjaikrishna";
 console.log(myName);  //  Output:  "jkjaikrishna"

using let keyword

let keyword is introduced in ES6 to avoid the redeclaration of variables in the same scope. But the declaration is possible in different block scopes.

//  Redeclaration in same scope
 let myName= "John Doe";
 console.log(myName);  // Output: "John Doe"
 ...
 ...
 let myName= "jkjaikrishna";
 console.log(myName);  //  Output:  Error: Uncaught SyntaxError: Identifier 'myName' has already been declared
//  Redeclaration in different scope
 let myName= "John Doe";
 console.log(myName);  // Output: "John Doe";
 ...
 ...
 function sampleFunction() {
     let myName = "Sam Cooper";
     console.log(myName);  //Output: "Sam Cooper"
 }
 ...
 ...
 sampleFunction();
 ...
 ...
 let myName= "jkjaikrishna";
 console.log(myName);  //  Output:  Error: Uncaught SyntaxError: Identifier 'myName' has already been declared

using const keyword

const variables are immutables. So redeclaration and value reassigning are not allowed in the same scope. For different scopes it's possible.

//  Redeclaration in same scope
 const myName= "John Doe";
 console.log(myName);  // Output: "John Doe"
 ...
 ...
 const myName= "jkjaikrishna";
 console.log(myName);  //  Output:  Error: Uncaught SyntaxError: Identifier 'myName' has already been declared
//  Redeclaration in different scope
 const myName= "John Doe";
 console.log(myName);  // Output: "John Doe";
 ...
 ...
 function sampleFunction() {
     const myName = "Sam Cooper";
     console.log(myName);  //Output: "Sam Cooper"
 }
 ...
 ...
 sampleFunction();
 ...
 ...
 var myName= "jkjaikrishna";
 console.log(myName);  //  Output:  Error: Uncaught SyntaxError: Identifier 'myName' has already been declared

Hoisting

The hot js interview question topic is here!! Hoisting is the JavaScript mechanism where,

variables and function declarations are moved to the top of their scope before code execution to avoid unexpected code breaking in the time of compilation.

using var keyword

The var keyword variables are hoisted to the top and declare its value as undefined


//  Hoisting with undefined value
 console.log(myName);  // Output: undefined
 ...
 ...
 const myName= "John Doe";

using let and const keyword

Like var keyword, it doesn't show undefined value, Instead of it they throws a Reference Error.


//  Hoisting with undefined value
 console.log(myName);  // Output: ReferenceError: 'myName is not defined'
 ...
 ...
 let/const myName= "John Doe";

One more thing...

The feature that we don't add in our list is value assigning and reassigning.

For var variables value assigning and reassigning can be done at any point in the code. This is also similar in the case of let keyword.

But const is something different in this case. The value to the const variables should be declared at the time of variable creation and it's can not be changed during code execution.

 // declaring a const variable without initializing.
 const myName; // Error: Uncaught SyntaxError: Missing initializer in const declaration
 ...
 //Reassigning a value to a const variable.
 const myName = "John Doe"; 
 ...
 myName = "jkjaikrishna";  //Error: Uncaught TypeError: Assignment to constant variable.

Even though push(), pop(), shift() and unshift() in a const array is possible.It's Because of the const variable stores only the reference to the array starting index.

 //push() to a const array.
 const fruits= ['mango', 'apple', 'orange'];

 fruits.push('strawberry');  //Output: ['mango', 'apple', orange','strawberry'];

//pop() from const array.
 const result = fruits.pop();  //Output: ['mango'];

//shift() on const array.
const animals= ['beer', 'wolf', 'tiger'];

 const result = animals.shift();  //Output: ['beer'];

 animals.unshift('lion');  //Output: ['lion', 'beer', 'wolf', 'tiger'];

Browser Support

All most all the browsers support var, let, and const keywords. You can check it here.

Conclusion

  1. How can we conclude this topic? It's here!
    • Scope: var declarations are function scoped, let/const are block-scoped.
    • Re-declaration: var can be updated and re-declared, let can be updated, but not re-declared, const cannot be updated or re-declared.
    • Hoisting: var is hoisted and initialized as undefined,let/const are hoisted without initialization and return Reference Error.

Top comments (0)