let
currentRoom
=
conference_room_a
;
// produces an error; no identifier
// called conference_room_a exists
You can use a literal anywhere you can use an identifier (where a
value is expected). For example, in our program, we could just use
the numeric literal 21.5 everywhere instead of using ROOM_TEMP_C.
If you use the numeric literal in a couple places, this may be OK.
But if you use it in 10 or 100 places, you should be using a constant
or variable instead: it makes your code easier to read, and you can
change the value in one place instead of many.
It is up to you, the programmer, to decide what to make a variable and what to make
a constant. Some things are quite obviously constants—such as the approximate value
of π (the ratio of a circle’s circumference to its diameter), or
DAYS_IN_MARCH
. Other
things, such as
ROOM_TEMP_C
, are not quite as obvious: 21.5°C might be a perfectly
comfortable room temperature for me, but not for you, so if this value is configurable
in your application, you would make it a variable instead.
Primitive Types and Objects
In JavaScript, values are either primitives or objects. Primitive types (such as string
and number) are immutable. The number 5 will always be the number 5; the string
"alpha"
will always be the string
"alpha"
. This seems obvious for numbers, but it
often trips people up with strings: when people concatenate strings together (
"alpha"
+ "omega"
), they sometimes think it’s the same string, just modified. It is not: it is a
new string, in the same way that 6 is a different number than 5. There are six primi‐
tive types that we will cover:
• Number
• String
• Boolean
• Null
• Undefined
• Symbol
Note that immutability doesn’t mean the contents of a variable can’t change:
let
str
=
"hello"
;
str
=
"world"
;
First
str
is initialized with the (immutable) value
"hello"
, and then it is assigned a
new (immutable) value,
"world"
. What’s important here is that
"hello"
and
"world"
are different strings; only the value that
str
holds has changed. Most of the time, this
Primitive Types and Objects | 37