var VS. let

 

 


 

Differences Between the var and let Keywords :

 

Var :


One of the biggest problems with declaring variables with the var keyword is that you can easily overwrite variable declarations :
var myName = "Hend";
var myName= "sara";
console.log(myName); \\ return Sara .

In this code ,the myName variable is originally declared as Hend, and is then overridden to be Sara .The console then displays the string Sara.

In a small application, you might not run into this type of problem. But as your codebase becomes larger, you might accidentally overwrite a variable that you did not intend to. Because this behavior does not throw an error, searching for and fixing bugs becomes more difficult.

 

 

Let :

A keyword called let was introduced in ES6,  to solve this issue with the var keyword.

If you replace var with let in the code above, it results in an error:

let myName= "Hend";
let myName= "Sara";

"The error can be seen in your browser console."

So unlike var, "when you use let, a variable with the same name can only be declared once."

so use let in your code to avoid the var issue.

 

Comments

Popular posts from this blog

Variable Scope in javascript

Shadowing

Hoisting