Tuesday, June 21, 2016

JavaScript: const vs let vs var

With the introduction of EcmaScript 6 (EcmaScript 2015), 2 new keywords(among a lot of other language features) are added:

  • const: creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
  • let: declares a block scope local variable

Although these 2 keywords seems simple, there is still some debate in the JavaScript community when to use ‘const’ vs ‘let’ vs ‘var’. Originally ‘let’ was stated as ‘the new var’, but others are promoting ‘const’ as the default.

Here are some general rules that I follow:

  • If a variable won’t be reassigned I use ‘const’
  • If a variable may be reassigned I use ‘let’
  • If someone points a gun at my head and I have no other choice, I use ‘var’ Winking smile

No comments: