What's the difference between let and var in JavaScript?


Hello, as I am not very well versed with javascript, I would like to know the difference between let and var keyword of javascript?(With example if possible)

Or Any reference link with proper details will also work, thanks


Asked by:- jon
0
: 2541 At:- 4/4/2018 7:22:16 AM
javascript let var







1 Answers
profileImage Answered by:- manish

let was introduced with ECMAScript 2015.

The let statement declares a block scope local variable, you can initialize it to a value just like var. So the main difference between let and var is, var declares variables globally or locally to entire function regardless of block scope. If you use the let in top of the functions or program, It does not create a global property like var. 

For example: 

function varExampleFunc(){
  var x =1;
  if (x === 1){
    var y =2;
  }
  console.log(x);
  console.log(y);
}

Output of the above code will be

1
2

As you can see we were still able to print the value of y var which was printed outside the function it was declared it

Now let's create another function like above but using let

function letExampleFunc(){
let x =1;
  if (x === 1){
    let y =3;  
    console.log(typeof(y)); 
  }
  console.log(x);
  console.log(typeof(y));
}

Output

number
1
undefined

as you can see, we were not able to print value of let y which was declared inside function

2
At:- 4/4/2018 11:34:15 AM
thanks, got it. 0
By : jon - at :- 5/11/2018 3:03:53 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use