Difference between var and let in JavaScript

Author : Sachin Sharma
Published On : 02 May 2023
Tags: javascript

Var

var is used to declare a variable in function scope manner and can declare a variable again even if it declared previously in the scope. var keyword introduced in ECMAScript1 feature.

Let me show you example

var x=10;    //declaration on var 

console.log(x);

Output: 10

now use x variable before declaration and see the output.

console.log(x);
var x=10;
console.log(x);

Output:
undefined
10

Let

let is also used to declare a variable in block scope manner and cannot declare a variable again if it declare previously in same scope.let keyword introduced in ES6 feature.

let x=10;
console.log(x);

Output:10

Now use variable x berfore declaration and see the output.


console.log(x);
let x=10;


Output: 
ReferenceError: Cannot access 'x' before initialization

 

I hope now clearily understad what is var and let keyword ,its uses and difference between them.

Comments

No comments have been added to this article.

Add Comment