4
If you’re already familiar with object-oriented programming in JavaScript, note that creating a symbol with
the
new
keyword is not allowed, and is an exception to the convention that identifiers that start with capital
letters should be used with
new
.
let
heating
=
true
;
let
cooling
=
false
;
Symbols
New in ES6 are symbols: a new data type representing unique tokens. Once you create
a symbol, it is unique: it will match no other symbol. In this way, symbols are like
objects (every object is unique). However, in all other ways, symbols are primitives,
lending themselves to useful language features that allow extensibility, which we’ll
learn more about in
.
Symbols are created with the
Symbol()
constructor.
You can optionally provide a
description, which is just for convenience:
const
RED
=
Symbol
();
const
ORANGE
=
Symbol
(
"The color of a sunset!"
);
RED
===
ORANGE
// false: every symbol is unique
I recommend using symbols whenever you want to have a unique identifier that you
don’t want inadvertently confused with some other identifier.
null and undefined
JavaScript has two special types,
null
and
undefined
.
null
has only one possible
value (
null
), and
undefined
has only one possible value (
undefined
). Both
null
and
undefined
represent something that doesn’t exist, and the fact that there are two sep‐
arate data types has caused no end of confusion, especially among beginners.
The general rule of thumb is that
null
is a data type that is available to you, the pro‐
grammer, and
undefined
should be reserved for JavaScript itself, to indicate that
something hasn’t been given a value yet. This is not an enforced rule: the
undefined
value is available to the programmer to use at any time, but common sense dictates
that you should be extremely cautious in using it. The only time I explicitly set a vari‐
able to
undefined
is when I want to deliberately mimic the behavior of a variable that
hasn’t been given a value yet. More commonly, you want to express that the value of a
variable isn’t known or isn’t applicable, in which case
null
is a better choice. This may
seem like splitting hairs, and sometimes it is—the beginning programmer is advised
to use
null
when unsure. Note that if you declare a variable without explicitly giving
it a value, it will have a value of
undefined
by default. Here are examples of using
null
and
undefined
literals:
Symbols | 45