DEV Community

Cover image for What is the difference between ' var ' and ' let ' ?
Davron
Davron

Posted on

What is the difference between ' var ' and ' let ' ?

Scoping :

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

function variablesTest() {
  var dav = "Dav";
  let ron = "Ron";

  console.log(dav, ron); // Dav Ron

  {
    var ilm = "Ilm"
    let hub = "Hub";
    console.log(ilm, hub); // Ilm Hub
  }

  console.log(ilm); // Ilm
  console.log(hub); // ReferenceError
}

variablesTest();
Enter fullscreen mode Exit fullscreen mode

The reason why let keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.

Hoisting :

While variables declared with var keyword are hoisted (initialized with undefined before the code is run) which means they are accessible in their enclosing scope even before they are declared :

function varCheck() {
  console.log(name); // undefined
  var name = "Davron";
  console.log(name); // Davron
}

varCheck();
Enter fullscreen mode Exit fullscreen mode

let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. The variable is said to be in "temporal dead zone"(which is probably gonna be the topic for my next article) from the start of the block until the initialization is processed :

function letCheck() {
  console.log(name); // ReferenceError
  let name = "Davron";
  console.log(name); // Davron
}

letCheck();
Enter fullscreen mode Exit fullscreen mode

Global Object Property :

At the top level, let, unlike var, does not create a property on the global object :

  var x = 'global'; // globally scoped
  let y = 'global'; // not allowed to be globally scoped
  console.log(this.x); // "global"
  console.log(this.y); // undefined
Enter fullscreen mode Exit fullscreen mode

Redeclaration :

In strict mode, var will allow you re-declare the same variable in the same scope while let raises a SyntaxError.

var name = "Davron"
var name = "John"
console.log(name) // 'Davron' is now replaced with 'John'

let surName = "Abdukhakimov"
let surName = "Doe" // SyntaxError Identifier 'surName' has already been declared
console.log(surName)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)