The difference Between Var, Let, And Const In Javascript

The difference Between Var, Let, And Const In Javascript

In javascript, you can declare a variable with var, let, and const keywords. But do you know the difference between them?. In this article, we will cover all you need to know about Var, Let, and const keywords.

The Var Keyword

The var keyword is one of the features of the ECMAScript 2009, also known as ES5 which is the older version of javascript.

The let keyword is a global scope or functional scope, this means that the variable declared outside function can be accessed globally and the one declared within the function can be accessed within that function.

The problem declaring a variable with var is that you can accidentally overwrite the existing variable. like so:

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 2

The Let Keyword

The let keyword was introduced in ES6, the newer version of javascript. The let keyword is blocked scope, meaning that it cannot be accessed outside the defined scope.

The common difference between the var keyword and the let keyword is that you cannot redeclare the variable that was defined earlier. it will result in an error.

Example:

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

The Const Keyword

The const keyword has the same function as the let keyword, the difference is, you cannot update the variable once you declare it "it's constant it cannot change".

Example:

// with let

let a = 20;
a= 11;
console.log(a);

// with const

const a = 20;

a =11;

// Uncaught TypeError: Assignment to constant variable.

That's all.

Thank you for reading.

lets connect: Twitter