Javascript const vs var

Learn what is the difference between const vs var in javascript.

They are two scopes to which variables are bounded in javascript
1.Function scope:- Variables declared inside functions.

function abcd(){
  //I am function scoped
  var a = 10; 
}

and

2.Block scope:-
Block or lexical scopes are the boundaries in which declared variables are not accessible outside it. This means the variables declared inside it are available inside given block and its sub-blocks.

Variables declared inside block level statements like for loop, if else, try catch etc.

while(true){
  // I am block scoped
  var a = 10;
}

Variables declared inside block scope can be accessed outside and this used to cause bugs, as it was common for a developer to assign different values to any variables. That is why Let and Const, two new ways of declaring variables in javascript are introduced in ES6.

Let us see what is the major difference between var and const in javascript.

We will first explore var.

var in javascript.

var are function scoped which means they are still accessible outside the block scope even though they are declared inside them.

//for loop is block scoped
for (var i = 0; i < 10; i++) {
  var iAmInside = "I am available outside of the loop";
}

console.log(iAmInside);
// I am available outside of the loop

//block scope
if(true){
  var inside = "Inside";
}
console.log(inside);
// Inside

//Function scoped
function myFunc(){
  var functionScoped = "I am available inside this function";
  console.log(functionScoped);
}
myFunc();
// I am available inside this function
console.log(functionScoped);
// ReferenceError: functionScoped is not defined

Explanation

In the first and second example, the value of the var leaked out of the block-scope and could be accessed from outside of it, whereas in the third example var was confined inside a function-scope and we could not access it from outside.

This happens because of Hoisting.

var are treated as if they are at the top of the function (or global scope) regardless of where the actual declaration occurs, this is called hoisting. For a demonstration see the following example.

var inside;  // hoisted on the top of the function. As there is no function so it is present in the global scope.
//block scope
if(true){
  var inside = "Inside";
}
console.log(inside);
//Inside

//Function scoped In this case value is hoisted inside the function
function getValue(condition) {
  if (condition) {
      var value = "blue";
      return value;
  } else {
      // value exists here with a value of undefined
      return value;
  }

  // value exists here with a value of undefined
}

console.log(getValue(true));   // blue
console.log(getValue(false));  // undefined


//While execution it is hoisted like this internally
function getValue(condition) {
  var value;  //value is hoisted as there is no value attached, so it is undefined.
  if (condition) {
      var value = "blue";
      return value;
  } else {
      // value exists here with a value of undefined
      return value;
  }

  // value exists here with a value of undefined
}
console.log(getValue(true));   // blue
console.log(getValue(false));  // undefined

We can redeclare var keyword any number of time we want.

var a = 10;
var b = 20;
var c = 30;

console.log(c);
// 30

const in javascript

const are declared same as var but it limits the variable scope to the given block. That is why we should declare const at the top of the block so that is accessible throughout the block and its sub-blocks.

variable declared with const cannot be redeclared or change by re-assigning the value. The value remains Constant.

const abc = "XYZ";
let abc; //SyntaxError: Identifier 'abc' has already been declared
abc = "pqr"; //TypeError: Assignment to constant variable.

For this reason the const variable should be initialised while declaring.

//Should be initialised while declaring
const XYZ; //SyntaxError: Missing initializer in a const declaration 

const is block scoped

if(true){
  const a = "I am inside";
  console.log(a);  // I am inside
}
console.log(a); //ReferenceError: a is not defined

However, the value a constant holds may be modified if it is an object.

const person = {
  name: 'Prashant',
  age: 25,
}

person.age = 26;
console.log(person.age); // 26

const declarations for objects do not prevent modification of those objects. A const declaration prevents modification of the binding and not of the value of the binding.

But this will result in the error.

const person = {
  name: 'Prashant',
  age: 25,
}

person = 26;
console.log(person); //  TypeError: Assignment to constant variable.

When to use const vs var in javascript

There is no as such rule stating where to use each of them, Everyone has different opinions.
But according to the properties of these three, it should be used as follows.

  • Use var for top-level variables that are shared across many (especially larger) scopes.
  • If there is no need to re-assign any variable. like const PI = 3.14; then use const.