The only blog needed to understand var, let and const
Tags: javascript, webdev, beginners, programming
Published: 2020-05-25 14:03:58

---
title: The only blog needed to understand var, let and const
published: true
description: A simple and fully executed article for explaining the var, let and const keywords in Javascript.
tags: javascript, webdev, beginners, programming

cover_image: https://dev-to-uploads.s3.amazonaws.com/i/cxp3kogtyughw2mp3emj.jpg
---

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!).
 


 ```javascript
//  Global Scope
 var varVariable = "John Doe";
 console.log(varVariable);  // Output: "John Doe"
 console.log(window.varVariable);  //  Output:  "John Doe" 
 ```

```javascript
//  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...

 

 ```javascript
//  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 
 ```


```javascript
//  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__.

 ```javascript
//  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 
 ```


```javascript
//  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. 


```javascript
//  Redeclaration in same scope
 var myName= "John Doe";
 console.log(myName);  // Output: "John Doe"
 ...
 ...
 var myName= "jkjaikrishna";
 console.log(myName);  //  Output:  "jkjaikrishna"
 ```

```javascript
//  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.

```javascript
//  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
 ```

```javascript
//  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.

```javascript
//  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
 ```

```javascript
//  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`


```javascript

//  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_.


```javascript

//  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_**.



```javascript
 // declaring a const variable without initializing.
 const myName; // Error: Uncaught SyntaxError: Missing initializer in const declaration
 ...
 ```

```javascript
 //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.


```javascript
 //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](https://caniuse.com/#search=let).
 
# 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.