-1

If I write ECMAScript 6 code, what will be better: to use only let and const or var too? I know the difference between them, but I want to know can I not use var at all? What is the best practice? I wanted to ask about Code Style

Oksana
  • 300
  • 2
  • 9
  • There's a good topic about this on another SE site http://softwareengineering.stackexchange.com/questions/274342/is-there-any-reason-to-use-the-var-keyword-in-es6 – roberrrt-s Nov 30 '16 at 15:46
  • The general consensus for the JS devs I know is "Use `const` until you can't, then use `let`" – Sterling Archer Nov 30 '16 at 15:47
  • 2
    Short and sweet - In ES6, `var` is the least specific of the three. It's usually best to use `const` when you know you don't want to change the value and use `let` in any other case. – Gavin Nov 30 '16 at 15:47
  • relevant: https://mathiasbynens.be/notes/es6-const – Jared Smith Nov 30 '16 at 15:51

1 Answers1

3

Nice write-up by Eric Elliot on this topic: (Emphasis mine)

[...] I favor const over let in ES6. In JavaScript, const means that the identifier can’t be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable.js and Mori, a const object can have properties mutated.)

If I don’t need to reassign, const is my default choice over let because I want the usage to be as clear as possible in the code.

I use let when I need to reassign a variable. Because I use one variable to represent one thing, the use case for let tends to be for loops or mathematical algorithms.

I don’t use var in ES6. There is value in block scope for loops, but I can’t think of a situation where I’d prefer var over let.

Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94