Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Using Constants with Arrays and Objects2:44 with Andrew Chalkley
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:04 The same goes for any value of a constant variable. 0:05 You cannot reassign strings, numbers, booleans, objects, and arrays. 0:08 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's literal 0:45 with a first_name key, with the string Imogen. 0:51 Let's attempt to modify these in the console here. 0:59 First, days, Let's use the push method to add another date to the array. 1:02 It didn't error. 1:14 It returned the number 2, meaning the new array length. 1:16 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, Again no error. 1:28 When we type person and hit Enter, we get an object literal back 1:38 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 overwritten completely. 1:55 For example, when I attempt to overwrite 2:00 person with another object literal. 2:06 It shows an error, because I'm attempting to reassign 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