Search in Help for developer site.

Thursday 27 September 2018

Difference between let and var keyword in javascript

Let and Var keyword in Javascript

Let and var keywords are used to declare variable in Javascript.

When to use Let over var keyword in Javascript.

It is recommended to use Let keyword over var keyword in javascript. Lets see why

Example 1: Declaration scope

In the below example, if we use let keyword and use the variable before its declaration it gives an error. Which is absolutely fine. 
console.log(orderId);  //Gives an error
let orderId = 10;

Now if we use var keyword and try to use the variable before its declaration it doesn't give any error. Which is strange. Not Recommended.
console.log(orderId); //undefined(not an error)
var orderId = 10;

Example 2: Scope in code block

Here let variable is bound to if block
if (true) {
let orderQty = 10;
}
console.log(orderQty);  //Error, Out of scope

var keyword is not bound to if block you can use outside the if block.
if (true) { 
var orderQty = 10;
}
console.log(orderQty);  //it will print 10, No error

So it is best practice to use let keyword over var keyword for declaring variable in Javascript.

3 comments: