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