1. 程式人生 > >Difference between ‘var’, ‘const’ & ‘let’ keywords

Difference between ‘var’, ‘const’ & ‘let’ keywords

Understanding ES6 | Difference between ‘var’, ‘const’ & ‘let’ keywords

The JavaScript language that we know is a superset of ECMAScrpt. The Core of the JavaScript is defined in ECMA-262, all the datatypes like variables, functions, Array, Objects etc… are defined in ECMA-262.

ECMAScript 6 was formalised in 2015 and was formally known as “ECMAScript 2015”. ECMAScript 6 includes very wide & completely new objects and patterns, syntax changes to new methods on existing objects. Main focus of ECMAScript 6 is toward solving problems that developers were facing.

In this blog I will explain the difference between var, let & const variable declaration.

The var keyword

Declaring variables using var keywords is traditional way in JavaScript. Variables declared with var are called hoisted. In this type of declaration vars are treated as if they were declared on top of the function; no matter wether you have declared even if in middle of the function. Let’s understand this with below example:

function getVars(condition) {   if (condition) {      var vars = "abc";      return vars;   } else {      // vars is available here but value of vars will be undefined     return null;   }   console.log(vars); // vars will print out - 'abc', if condition is true}

If you are a C or other language developer and new to JavaScript, you might think that the value of vars

will be created only when condition returns true. But in JavaScript the variable vars will be created regardless of result of the condition. It is because of the JavaScript engine changes the getVars function to look like as below:

function getVars(condition) {   var vars; // vars will get hoisted on top of function
   if (condition) {      vars = "abc";      return vars;   } else {      // vars is available here but value of vars will be undefined      return null;   }   console.log(vars); // vars will print out - 'abc', if condition is true}

As you can see from above code that the variable vars is declared on top of the function but it’s initialization happens on the same place as before. So in case of the condition returns false the variable vars is still accessible with undefined value.

It is because of this behaviour many new JavaScript developer might misunderstand the variable hoisting and end up in bugs. Because of this reason ECMAScript 6 has introduced Block-level declaration to make the variable more powerful and introduced two more datatype called let and const.

The let keyword

The let keyword declaration is same as of the var keyword. You can basically replace the var keyword with let and that’s it. Only difference is let will limit the scope of the variable only inside the block level (not in the function level). Let’s understand the above example with let:

function getVars(condition) {   if (condition) {      let vars = "abc";      return vars;   } else {      // vars is not accessible here return null;   }   console.log(vars); // vars will throw error regardless of the condition result.}

The let declaration is a block level declaration so once the function flows out of the if (condition) { ... } block the vars variable will become inaccessible to the function. That is why it will throw an error when you try to call it within console.log(vars);. So to make sure the variable declared with let be accessible through out the function, you need to declare it on top of the function specifically as below:

function getVars(condition) {   let vars;
   if (condition) {      vars = "abc";      return vars;   } else {      // vars will be accessible here return null;   }   console.log(vars); // vars will print out - 'abc', if condition is true else it will print 'undefined'.}

The const keyword

ECMAScript 6 has also included one more way to declare a variable named const. The variable declared using const will be constant through out the function and cannot be change it once declared. That is why every const variable must be initialized on its declaration as below:

const firstName = "Ashish";   // valid constant
// throws errorfirstName = "Panchal";
// invalid constantconst lastName;        // it needs to be initialized as well

Same as let declaration const declaration is also a block-level declaration, it means variable declared with const will not be accessible outside the scope of block.

if (condition) {   const vars = "abc";}
// throws errorconsole.log(vars);    // vars will not be accessible here

In the above code vars is declared with const and once the execution of if condition finished, the vars variable will not be accessible outside of the block.

Any variable that is declared with var or let in the code cannot be used to declare it again with const, see example below:

var vars = "abc";let num = 50;
// both throws errorconst vars = "def";const num = 100;

I hope the above description of var, let and const datatype helps understanding them clearly. In case any query or suggestion please let me know in below comment box.