Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Using constants prevents values from being reassigned but how do they work with arrays and objects?
We've seen that you cannot reassign a
constant variable in the case of a number
0:00
or a string.
0:05
The same goes for
any value of a constant variable.
0:05
You cannot reassign strings, numbers,
booleans, objects, and arrays.
0:09
Unlike strings, numbers, and booleans,
objects in arrays have methods and
0:14
properties that modify the objects or
array.
0:18
Do they still work with const?
0:22
First we'll declare a variable,
which is a constant called days.
0:24
This will contain an array
with a single string "Monday".
0:33
Second we'll declare
another constant variable
0:39
person that contains an object
literal with a {first_name}.
0:44
Key, with the string "Imogen".
0:52
Let's attempt to modify these
in the console here, first days.
0:59
Let's use the push method to
add another day to the array.
1:06
It didn't error, it returned the number 2,
meaning the new array length.
1:14
If we type days, and hit Enter,
we get Monday and Tuesday returned.
1:21
Let's try and add a last_name
property to the person object.
1:28
Again no error.
1:36
When we type person and
hit Enter we get an object
1:38
literal back with the first_name and
last_name properties.
1:42
So what's happening here?
1:47
Const doesn't prevent complex objects like
arrays and objects from being modified.
1:49
It just prevents them from being
reassigned or over written completely.
1:55
For example, when I attempt to override
2:00
person with another object literal.
2:06
It shows an error, because I'm attempting
to re-assign person with a new object.
2:16
However, if I modified the first name.
2:25
To equal another value,
Andrew, I don't get any errors.
2:32
You need to sign up for Treehouse in order to download course files.
Sign up