Difference between var and let keyword in JavaScript

Difference between var and let keyword in JavaScript

In the early days of JavaScript there is only one way of declaring variable that is using var keyword With the introduction of ES6 in 2015 two more keywords , let and const come in the tech also In this article we will talk about the basic difference between var and let keywords using examples and their scopes

var keyword in js

scope : The scope of the var keyword is function or global scope

For e.g.

  var a = 6 

  function variable() {
         console.log(a) 
   }

    variable() 
    console.log(a)

Output :

6
6

In the above example we declare a variable ‘a' with a value 10 globally and in the function log the value of ‘a' When we print the value of ‘a' outside the function and call the function also it gives the same results that means variable declare using var keywords are globally or function scoped

  1. The variable that is being declared inside a function using var keyword cannot be accessible outside the function

For e.g.

function example() {
      var a = 8 
      console.log(a) 
}

example()    
console.log(a)

Output :

 8 
Error : as 'a' cannot be accessible outside the function
  1. If we uses the variable before declaration it initializes with a undefined value
console.log(a) 

var a = 20

Output :

undefined

let keyword in js

Scope : Block scoped that means it can't accessible outside the block

let a = 11

if(a==11){
    let b = 20
    console.log(b)
}

console.log(a)
console.log(b)

Output :

20
11
b is not defined
  1. If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error.
console.log(a) 
let a = 20

Output :

a is not defined 
Uncaught ReferenceError: Cannot access 'a' before initialization

For more details you can go to this link