I'm from a Java background and started learning JavaScript.
Declaring variables in JavaScript using the keyword let
sounds like is uses similar scope rules of declaring variables in Java. The concept of hoisting in JavaScript is confusing (consider my C++/Java background) and I don't see any pitfalls in using let
in place of var
.
Is my understanding correct?
NO, let is the new block scoping var . That statement emphasizes that let should replace var only when var was already signaling block scoping stylistically. Otherwise, leave var alone.
The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while variable declared with var has the global scope. So we can say that var is rather a keyword which defines a variable globally regardless of block scope.
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.
Yes, your understanding is correct.
Some experts even recommend solely using let
everywhere, if it is available in your environment (Douglas Crockford said it in his Pluralsight course JavaScript the Good Parts).
ESLint
even has a rule not to use var
in ES6 Environments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With