Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can let replace var in JavaScript? [duplicate]

Tags:

javascript

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?

like image 540
FullMoon Avatar asked Sep 26 '15 10:09

FullMoon


People also ask

Can I replace VAR with LET?

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.

Which is better let or VAR in JavaScript?

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.

Is VAR and let the same in JavaScript?

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.


1 Answers

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.

like image 155
Domysee Avatar answered Oct 24 '22 13:10

Domysee