Declaring Variables in Ecmascript 6
ES6, JavaScript
Variables are used as symbolic names for values. Variable names are known as ‘identifiers’. In JavaScript, identifiers are case-sensitive and must begin with a letter, underscore or dollar sign.
TLDR;
Don’t use var
to declare variables - use const
where possible and let
otherwise. Use a transpiler like babel to sort things out for pre-ES6 browsers.
Variable Declaration
Ecmascript 6 introduced the let
and const
statements for declaring variables. This means that variables can be declared as follows:
var
: Declare a variable, optionally assigning a valuelet
: Declare a block-scoped local variable, optionally assigning a valueconst
: Declare a block-scoped read-only constant
Scoping
Variables defined with var
and const
are function scoped, whereas variables defined with let
are block-scoped.
Block scoping basically means that the variable scope is limited by the enclosing {}
- so a variable is declared by means of let
is limited in it’s scope to the block, statement or expression in which it is used.
This can be useful when dealing with loop iterations - when the counter variable is defined by var
, all loop iterations (confusingly) share the same function-scoped counter variable, leading to unexpected results. Declaring the index with let
produces a much more intuitive result:
Source: SE answer
const
This is another way to declare variables - like let
, variables const
has block scope. Variables declared in this way are read-only constants.
You can’t change the value of a constant by re-assignment, and it can’t be re-declared. However, the value held by a constant is not immutable. If you define an object using const
, the object contents can be amended.
A constant can’t have the same name as a function or variable in the same scope. Constants can be declared with uppercase or lowercase letters - a common convention is to use all-uppercase letters.
A constant can have global scope (i.e. on the window object) if defined outside a block.
If you don’t need to change a variable, it’s probably a good idea to use const
. This helps to Minimize Mutable State - Mutable state makes mistakes more likely.
References
- SE answer with a good description of why
let
is better thanvar
- Douglas Crockford discussing the issue
- Useful YouTube video from funfunfunction - as well as being really useful, this guy is very entertaining!
- MDN on
const
- MDN on
let
comments powered by Disqus