2

"Let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope." - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Which one should be used in modern javascript code? let or var?

Edit: I checked the Google JavaScript Style Guide and it states "Declarations with var: Always" (https://google.github.io/styleguide/javascriptguide.xml)

But in the tutorial at javascript.info (not sure if this is an official JavaScript website or not) it says to use let (https://javascript.info/variables)

I'm assuming I should stick to what Google recommends, but am still open to answers.

Second Edit: The above is not the most recent Google JavaScript Style Guide. In that one it states: "Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used".(https://google.github.io/styleguide/jsguide.html#features-local-variable-declarations)

justin
  • 553
  • 1
  • 7
  • 18
  • 1
    Whichever one makes sense for your own code. Usually it's better to scope variables as locally as possible, except when it isn't. – Pointy Aug 15 '18 at 17:35
  • 1
    Your referenced style guide is out of date. https://google.github.io/styleguide/jsguide.html#features-local-variable-declarations - the problem isn't so much good practice as, it depends on what platform your building for. Many people require IE11 and below. ES6 still isn't particularly friendly. – zfrisch Aug 15 '18 at 17:41

1 Answers1

7

In modern JS, use let or const whenever possible and appropriate. The semantics match more closely those how variables and constants work in other programming languages, and you'll avoid a lot of cognitive overhead caused by all the peculiarities that var has, compared to other languages (such as hoisting).

Chris W
  • 938
  • 7
  • 13