Object Fundamentals in JavaScript
Six rules decide almost every object question. Free to watch, with a free slide PDF and practice questions.
Chapters
- 0:00 Object Fundamentals in JavaScript
- 0:37 Quick recap: choosing the right function
- 1:15 Six rules decide almost every object question
- 2:01 One table holds the whole lesson
- 3:21 Two objects are equal only if they are the same object
- 4:40 Shorthand, computed keys, and method shorthand
- 5:36 Destructuring unpacks properties into variables
- 6:36 A default fills in for undefined, never for null
- 7:32 Spread makes a new object; assign edits its target
- 8:29 A copy of a copy still shares the inner object
- 9:26 keys, values, and entries list own properties
- 10:25 Object.freeze locks one level only
- 11:15 this is set by how the method is called
- 12:06 An arrow function is a poor object method
- 12:52 Lookup walks the prototype chain until null
- 14:00 Objects passed into LWC are read-only
- 14:52 Six terms to say in your own words
- 15:36 Copy it three ways, then change the inner object
- 16:37 Eight questions, closed book
- 17:56 A developer runs the following code. What is logged?
- 18:34 Bergen true
- 19:30 Four habits for every object question
- 20:10 Now test it, then move to classes
Test yourself on object fundamentals in javascript
Practice questions for this lesson come with a full explanation of why each answer is right or wrong, and link back to the exact moment in the video.
Take the free diagnosticTranscript
Read the full lesson text
Object Fundamentals in JavaScript 0:00
Welcome to module two, lesson two: object fundamentals in JavaScript. This module is called Objects, Functions, and Classes, and it carries twenty five percent of the exam. Objects are everywhere in JavaScript, and the exam asks what happens when you compare them, copy them, lock them, or call their methods. In this lesson we cover how objects are built, compared, copied, frozen, and inherited. By the end, you will be able to predict how objects are compared, copied, frozen, and called, and spot the shallow copy trap before you run it.
Quick recap: choosing the right function 0:37
Before we start, a quick recap from lesson one, where we chose the right function. First, declarations hoist, but a const function expression waits until its line runs. Second, this follows the call, while an arrow function keeps the enclosing one. Third, default and rest parameters give us flexible signatures, and closures remember the scope they were created in. And fourth, our rhythm in every lesson is rule, trace, trap, proof. Today we move from the functions to the objects they work on: how objects are built, compared, copied, locked, and inherited.
Six rules decide almost every object question 1:15
This domain is twenty five percent of the exam, so objects are worth real attention. This lesson boils down to six rules. There are three ways to copy an object, and you will meet all of them. First, objects compare by reference. Second, destructuring defaults only fill in for undefined. Third, copies are shallow. Fourth, freeze is shallow too. Fifth, this follows the call. And sixth, property lookup walks the prototype chain. We will also cover shorthand syntax, computed keys, keys and entries, and read only objects in L W C. Rules three and four are the shallow ones. They produce the most questions, so we slow down there.
One table holds the whole lesson 2:01
Here is the whole lesson on one slide. Every remaining slide is one row of this table, with an example. Pause here and read each row aloud when you finish the lesson. Equality. The rule: objects compare by reference. The trap: two objects with the same properties are still not equal. The safe habit is to compare the fields you care about. Destructure. The rule: a default needs undefined. The trap: null keeps null. The safe habit is to know where the data comes from. Copy. The rule: spread and assign copy one level. The trap: nested objects are shared. The safe habit is "structured clone". Freeze. The rule: it locks the top level only. The trap: a nested object still changes. The safe habit is to freeze each level. This. The rule: it is set by the call site. The trap: a detached method or an arrow method. The safe habit is method shorthand. And L W C input. The rule: it is proxied and read only. The trap: the invalid mutation error. The safe habit is to make a shallow copy first. One practical rule ties it together: objects are references, and copy and lock only go one level deep.
Two objects are equal only if they are the same object 3:21
Our first rule: two objects are equal only if they are the same object. An object literal is a reference type. Look at the code. We create a, an object with id one, and b, another object with id one. The expression a triple equals b is false, and a double equals b is false too, because they are two different objects that merely look alike. But c points at the same object as a, so a triple equals c is true. Next, brackets. The variable key holds the string make, and the brackets read that name, so the car gets a make property of Ford. Reading car dot make and car with the string make in brackets both give Ford. So an object literal is a reference type. Same properties, different objects: triple equals and double equals are both false. Brackets read a name held in a variable. And a missing property is undefined, while the delete operator removes one. The exam point: two variables pointing at the same object are equal, but two look alike objects are not. Remember that dot notation needs a valid name. Brackets handle dynamic names, and names that are not valid identifiers. Getters and setters look like properties, but they run functions.
Shorthand, computed keys, and method shorthand 4:40
This slide is about writing objects in less space. Shorthand, computed keys, and method shorthand. Look at the code. With name and age already declared, writing name, age inside the braces uses each variable as both key and value. That is shorthand properties. Then the square brackets around param make a key from an expression, so the user gets a role property set to admin. That is a computed key, and it is evaluated at runtime, so the brackets can hold any expression. Next, greet followed by parentheses drops the function keyword. That is method shorthand, and inside it, this dot name reads the name from the object. And get label is a getter. Get and set run functions on read and write, even though they look like plain properties. The practical rule: shorthand is only a shorter way to write the same object.
Destructuring unpacks properties into variables 5:36
Destructuring unpacks properties into variables. Look at the code. Braces with id and "is verified" on the left, and user on the right, make two variables named like the properties. That is the basic form. Next, id colon user id. Rename syntax puts the property on the left and the new variable on the right. So the variable is user id, and there is no variable named id. Then a, followed by the rest syntax and others. The rest must come last, and it copies the remaining own properties. So others is an object with b and c. And when you destructure into variables that already exist, wrap the whole statement in parentheses, otherwise the braces are read as a block. Nested patterns work too, and a parameter can default to an empty object. The exam point: with id colon user id, only user id exists. There is no variable named id.
A default fills in for undefined, never for null 6:36
Now a trap about destructuring defaults. The wrong shortcut says: a missing or empty value always takes the default. The correct exam test says: use the default only for a missing property or undefined. Look at the code. We destructure a, b, and c, each with a default of five, from an object where a is null and b is undefined, and c is missing entirely. Logging them gives null, five, five. Trace it. A is null, and null is a value, so it keeps null. B is explicitly undefined, so it takes five. C does not exist at all, so it takes five as well. The same goes for the empty string. A property holding an empty string keeps the empty string. The exam point: null and the empty string are values, so they keep their value. Only a missing property or the value undefined triggers the default.
Spread makes a new object; assign edits its target 7:32
Now two ways to combine objects: spread and Object dot assign. Look at the code. Merged is built with spread of defaults, followed by size three. That makes a new object, and defaults is unchanged. Then Object dot assign on defaults, with size two, mutates defaults in place and returns it. So when we log both, merged has size three, and defaults has size two. The rule has four parts. Spread copies own enumerable properties into a new object. On a key collision, the last value wins. Assign changes its target in place. And assign throws on a null target, while null sources are ignored. One more detail: assign triggers setters on the target, and spread does not. Spread also does not copy the prototype or non enumerable properties. The practical rule: spread builds a new object, and assign edits the first argument.
A copy of a copy still shares the inner object 8:29
This is the most tested trap in the lesson: a copy of a copy still shares the inner object. The wrong shortcut says: spread makes an independent copy. The correct exam test says: spread and assign copy one level, and you use "structured clone" for a deep copy. Look at the code. Original has a name and an address object. We spread it into copy, then set copy dot address dot city to Reno. Now we log original dot address dot city, and it says Reno. Why? Only the top level values were copied. The address object itself is the same reference in both, so a change through one is visible through the other. The last line, "structured clone" of original, gives a real deep copy, with no shared references. The exam point: Object dot assign with an empty object and a, and spread of a, both share nested objects with a.
keys, values, and entries list own properties 9:26
Next, listing an object's own properties with keys, values, and entries. Look at the code. Object dot keys of o returns b and a, in that order. Object dot values returns one and two. And Object dot entries returns an array of key and value pairs. The loop below pairs entries with array destructuring in a for of loop. That is the iteration pattern to remember. Now the second object, with keys one hundred, two, and seven. Numeric looking keys come out first in ascending order, so keys returns two, seven, one hundred, and they are strings. So Object dot keys returns own enumerable string keys, as an array. Entries gives key and value pairs, and the keys are strings. Numeric looking keys sort first, in ascending order. And a for in loop also walks the prototype chain. The exam point: Object dot keys leaves out inherited properties, and for in includes them.
Object.freeze locks one level only 10:25
Object dot freeze locks one level only. Look at the code. The employee is a frozen object, with a name and a nested address. Setting the name is ignored. But setting address dot city to Bergen works, because the address object was never frozen. So the log says Bergen, and "is frozen" says true. Here is the rule. A frozen object allows no adding, removing, or changing of top level properties. Freeze returns the same object, not a frozen copy. A blocked write fails silently, or throws a "type error" in strict mode. And "is frozen" reports the state of the top level only. The exam point: freeze is shallow, so employee dot address dot city can still change. Freezing the outer object does not freeze the object inside it.
this is set by how the method is called 11:15
Rule five: this is set by how the method is called. Look at the code, in strict mode. The method reg returns lost if this is undefined, otherwise it returns this dot name. Calling o dot reg gives the name o, because the call has an object in front of the dot. Now we pull the method off the object into f, and call f. There is nothing in front of the dot, so this is undefined in strict mode, and the result is lost. So obj dot method sets this to obj. A method pulled off its object loses this. Detached, this is undefined in strict mode, and the global object otherwise. And one function on two objects sees each in turn. The practical rule: look at the call site, not at where the function was written. Same function, different call, different this.
An arrow function is a poor object method 12:06
Now the trap: an arrow function is a poor object method. The wrong shortcut says: an arrow function in an object gets that object as this. The correct exam test says: an arrow takes this from its enclosing scope, so use method shorthand. Look at the code. Obj has b, an arrow, and c, a method. Calling obj dot b logs undefined, plus the global object, because the arrow has no this of its own, so there is nothing for the object to supply. Calling obj dot c logs ten, plus obj, because the method gets this from the call. The exam point: call, apply, and bind cannot change an arrow function's this.
Lookup walks the prototype chain until null 12:52
Rule six: lookup walks the prototype chain until null. Look at the code. Animal proto has a type and a show method. Object dot create of animal proto makes fish, linked to that prototype. Then we set fish dot type to Fishes. That creates an own property, which shadows the inherited one. Now fish dot show returns Fishes, even though show lives on the prototype. The method gets this from the caller, and the caller is fish. Calling animal proto dot show returns Invertebrates. And Object dot "has own" of fish and show is false, because show is not an own property. So every object links to a prototype, until null ends the chain. Object dot create sets the link, and "get prototype of" reads it. Setting a property makes an own property that shadows the inherited one. And "has own" checks own keys. The exam point: fish dot show returns Fishes because this is fish, not the prototype. Object dot create of null makes an object with no prototype at all. Setting the prototype after creation is possible, but discouraged.
Objects passed into LWC are read-only 14:00
Now the Salesforce part: objects passed into L W C are read only. Look at the code. In a child component, this dot record dot msg equals hi fails with an invalid mutation error. The message says that the object is read only. The fix is at the bottom: change a shallow copy, made with spread, instead. The reason is that a component treats values passed to it as read only. Objects and arrays from a parent are wrapped in a proxy, and changing one gives the invalid mutation error. So make a shallow copy, such as with spread, then mutate the copy. The exam point: to change data from a parent, copy it first, then change the copy. This comes from the Lightning Web Components Data Flow guide. Primitive values are copied, so only objects and arrays are affected.
Six terms to say in your own words 14:52
Time for the key terms. Say each one in your own words. An object initializer is the literal braces syntax that creates an object. A shorthand property means a in braces is the same as a colon a. A computed property name is an expression in square brackets, with the key evaluated at runtime. A shallow copy copies top level values, while nested objects stay shared. An own property is a property set directly on the object itself. And the prototype chain is the linked objects searched for missing properties, ending at null. Pause the video now. Cover each card and explain the term aloud, then continue.
Copy it three ways, then change the inner object 15:36
Now the proof. This lab comes from the curriculum. Copy it three ways, then change the inner object. Look at the code. Original has a name and a nested address. C one is a spread copy, c two uses Object dot assign, and c three uses "structured clone". For each copy, we set the name to Max and the city to Reno. Predict, for each copy, what original shows after the two changes, and which copies share the nested address. Pause the video and try it, then run it in Node. Copy one, the spread. Original name is still Rex, but the address is shared, so city is Reno. Copy two, Object dot assign. Same result: name is Rex, the address is shared, and city is Reno. Copy three, "structured clone". Name is Rex, the address is separate, and city is still Austin. A wrong prediction is the lesson. Go back to the slide that explains it.
Eight questions, closed book 16:37
Self check time. Eight questions, closed book. Answer out loud, then I will reveal each answer. One. Is an object with id one strictly equal to another object with id one? False. Two. Destructuring a with a default of five from an object where a is null. What is a? Null. Three. The same, but a is undefined. What is a? Five. Four. Spreading x one and then x two into one object. What is x? Two, because the last value wins. Five. Freeze an object with a nested object, then change the nested value. What is it? Two, because freeze is shallow. Six. Object dot keys of an object created from a prototype with p. What comes back? An empty array, because keys skips inherited properties. Seven. A method pulled off its object and called alone, in strict mode. What is this? Undefined. And eight. Fish inherits show. Does Object dot "has own" of fish and show return true? False. How many did you get? Anything you missed, go back to that slide.
A developer runs the following code. What is logged? 17:56
Time for a practice question. This is a predict question. Pause the video and decide which writes freeze blocks before you read the options. A developer runs the code shown. What is logged? Option A: Oslo, true. Option B: Bergen, false. Option C: Bergen, true. Option D: Oslo, false. This question combines the two shallow rules from this lesson. Ask which object was frozen, and which object the write touches. Pause now, and I will give you the answer on the next slide.
Bergen true 18:34
The answer is C. Bergen, true. Here is why. Freeze locks only the top level. The write goes to employee dot address dot city, and the address object is a different object that was never frozen, so the city changes to Bergen. And "is frozen" of employee still reports true, because the outer object "is frozen". Now the wrong options. A says Oslo, true. That assumes freeze blocks the nested write, but freeze does not reach the nested object. B says Bergen, false. The nested write does work, but the top level object is still frozen, so "is frozen" is true. D says Oslo, false. That is wrong on both counts: the city changes, and employee "is frozen". The takeaway: freeze protects the top level only, and "is frozen" reports only that level.
Four habits for every object question 19:30
Let's consolidate. Four habits for every object question. Reference: objects compare by identity, and a copy is a new object only at the top level. Copy: spread and assign go one level. Use "structured clone" for a deep copy. Lock: freeze is shallow, and L W C inputs are read only, so copy before you change. Call: this follows the call site, and arrows and the prototype chain follow their own rules. Remember: ask what is a reference, then ask how many levels the operation reaches. If you can say these four cards from memory, you've got the lesson.
Now test it, then move to classes 20:10
That completes lesson two. Now test it, then move on to classes. The flow is: read it, predict it, test it. Read it is the six object rules. Predict it is applying the rule. And test it is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Class Fundamentals, we see how classes build on prototypes: constructors, members, and inheritance. See you there.