Let and Var Difference JavaScript

Let and Var Difference JavaScript

In javascript, we can define variables in 4 ways

variables.png

In this article, we talk about the difference between var and let.

Let and Var

In JavaScript, the keywords var and let are used to declare variables.

The let keyword was introduced in 2015 known as ES6(ES2015). And it's the best way to declare variables.

Why do we have to use the let over the var?

1. Scoped

var

  • var is a function scoped
  • Declare a variable with var inside a function that can be used anywhere in the function.

varscoped.png

In the above example, var a is function scoped so it can be used anywhere inside the function.

let

  • let the keyword is block scoped
  • Declare variables with the let keyword inside the { } block that can not be accessed from outside that block.

letscoped.png

In the above example, let a is declared as a function scoped so it can be accessed from anywhere right? But let b is declared as a block-scoped inside the if block statement so it can not be accessed from the outside of the if block statement.

2. Redeclare

var

  • In var can be possible to redeclare the same variable name it will not throw an error.

redclarevar.png

let

  • But in let can not be possible to redeclare the same variable name it will throw an error.

redclarelet.png

3. Hoisting

Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration.

var

  • In var hoisting is possible. we can use the variable before its declaration.

hoistvar.png

let

  • But In let does not allow us to hoist it will throw an error.

hoistlet.png