We know that JavaScript allows us to declare variables with either var or let. The question now is how to tell when to use var or let.
The following text explains the main difference between let in JavaScript and var.
Let and var are different in that the scope of a variable with let is restricted to the block it is declared in, while var has a global scope. We can therefore say that var is a keyword which defines a variable globally, regardless of its block scope.
Let’s scope is not limited to the block it is declared in. Variables with let are not added to the global window object, even if they are declared outside of any block. If the global definition of var is made, we can still access variables with var through the window object.
Because let variables have a limited scope, they are often used when the variables can be used only in certain situations, such as while loops or within the scope of if condition. Var variable, on the other hand, is used when the variable value must be less modified and can be accessed globally.
Another difference between let and var is that variable with var may be changed to another value, while variable cannot be changed if it has been defined with let.
Example representing difference between var and let
let a = 'hello'; // globally scoped var b = 'world'; // globally scoped console.log(window.a); // undefined console.log(window.b); // 'world' var a = 'hello'; var a = 'world'; // No problem, 'hello' is replaced. let b = 'hello'; let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
Leave a Reply