Sunday, November 25, 2018

Difference between let and var in Javascript

This tutorial explains basic uses and difference between Let and Var in javascript. When any developer is working in JavaScript, often uses let, var keywords. Most of us use it randomly as there has been a lot of confusion regarding the use of let and var in JavaScript.

Let Scope :
  • The scope of a variable defined with var is function scope or declared outside any function, global.

Var Scope :
  • The scope of a variable defined with let is block scope.
Difference between let and var in Javascript

Global window object

When let and var defined globally, then the let variable will not be added to the global window object.
var x = "This is variable x";
let y = "This is variable y";

console.log(window.x); 
console.log(window.y);

Output:
---------------------
> "This is variable x"
> undefined

Re-declaring Variables :

let variables cannot be re-declared while var variable can be re-declared in the same scope.
var x = 100 ;
var x = 500 ;

console.log(x); 
console.log(x); 

Output:
---------------------
> 500
> 500

We cannot do the same thing with let.

Example -1 :
let x = 100 ;
let x = 500 ;

console.log(x); 
console.log(x);

Output:
---------------------
Error: Identifier 'x' has already been declared

Example -2 :
var x = 100 ;
let x = 500 ;

console.log(x); 
console.log(x);

Output:
---------------------
Error: Identifier 'x' has already been declared

Example -3 :
let x = 100 ;
var x = 500 ;

console.log(x); 
console.log(x);

Output:
---------------------
Error: Identifier 'x' has already been declared


Block Scope :

Variables declared Locally (inside a function) have Function Scope.

For loop using var variable: -
for(var i=0; i<10; i++){
console.log(i); 
}
console.log("Get final value :- "+ i); 

Output:
---------------------
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> "Get final value :- 10"

For loop using let variable: -
for(let i=0; i<10; i++){
console.log(i);  // print the value 
}
console.log("Get final value :- "+ i); // not accessible outside the functional scope.

Output:
---------------------
Error: i is not defined

Function Scope :

let and var variables work the same way when used in a function block.
function display(){
  var x = 10 ;
  let y = 30 ;
  
  console.log(x); 
  console.log(y); 
}

display()

Output:
---------------------
> 10
> 30

This is all about  let and var scope in Javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment