in

What are the differences between var, let and const in JavaScript?


JavaScript has three variable declaration statements: var, let and const. The latter two were added in ES6, whereas var existed since previous versions. One of the first things to notice is that const defines constants (i.e. values that will not be reassigned), whereas var and let define variables. Yet, var behaves differently from both let and const in various other ways.

Scope

Variables declared with var are function scoped, in contrast to variables declared with let or const which are block scoped.

const scopeExample = () => {
  var a = 'var';
  let b = 'let';
  console.log(a, b); 

  {
    var c = 'var';
    let d = 'let';
    console.log(c, d); 
  }

  console.log(c); 
  console.log(d); 
};

If you want to learn more, we have an article covering JavaScript variables and scopes in more depth.

Hoisting

While variables declared with var are hoisted to the enclosing scope, variables declared with let or const are not initialized until their definition is evaluated.

const hoistingExample = () => {
  console.log(a); 
  var a = 'var';
  console.log(a); 

  console.log(b); 
  let b = 'let';
  console.log(b); 
};

If you want to learn more, we have an article covering JavaScript hoisting in more depth.

Global object property

At the top level, variables declared with var, unlike ones declared with let or const, create a property on the global object.

var a = 'var';
let b = 'let';

console.log(window.a); 
console.log(window.b); 

Redeclaration

In strict mode, variables declared with var can be re-declared in the same scope, whereas this is not allowed for variables declared with let or const.

'use strict';
var a = 'var1';
var a = 'var2';

let b = 'let1';
let b = 'let2'; 


Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

GIPHY App Key not set. Please check settings

Cybersecurity Jobs: Opportunities, Skills to Acquire, and Learning Resources 

Heavily Policed ‘Justice For J6’ Rally Brings Sparse Crowd – And Minimal Violence – To Capitol