Introduction : javascript use of let and var
In JavaScript, let is a keyword that is used to declare a block scoped variable. Usually, the var keyword is treated as a normal variable, but the variables declared using the let keyword are block scoped, javascript use of let and var
let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope, javascript use of let and var.
Example: javascript use of let and var
let x = 2; if (x === 2) { let x = 3; console.log("Inside scoped:" + x); } console.log("Outside scoped:" + x);
OutPut :
- Inside scoped: 3
- Outside scoped: 2
As per above example we are using here let key word, first will assign variable let x value to 2 and then after inside if block will re-assign variable let x value to 3
once code is executed will get re-assign value of let x=3 inside if code block only, but outside the code block it access the old value this is due to code-block variable accessibility of let keyword.
if here will use var key word instead of of let keyword then will get out 3 for both inside of if-block and outside of if-block as mensioned below programe.
Example:
var x = 2; if (x === 2) { var x = 3; console.log("Inside scoped:" + x); } console.log("Inside scoped:" + x);
OutPut :
- Inside scoped: 3
- Outside scoped: 3