JavaScript Objects Demystified

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Objects Demystified

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

let channing = { name: 'magic mike', gender: 'male' };

console.log(channing.name); // 'magic mike'

channing.name = 'tatum';
console.log(channing.name); // 'tatum'

channing.skill = 'dance';
console.log(channing.skill); // 'dance'

channing.born = 1980;
console.log(channing.born); // 1980

channing.planet = { name: 'earth' };
console.log(channing.planet.name); // 'earth'

console.log(channing); // { name: 'tatum', gender: 'male', skill: 'dance', born: 1980, planet: { name: 'earth' } }

console.log(channing.citizenship); // undefined

Mutability

Below example demonstrates mutability of objects vs primitive values.

/** Objects are mutable references */
const channing = { name: 'magic mike' };

console.log(channing.name); // 'magic mike'

channing.name = 'tatum'; // ✅

console.log(channing.name); // 'tatum'

channing = { name: 'tatum' }; // ❌ ERROR: cannot reassign const

/** Simple primitives are immutable values */
const person = 'channing tatum';
console.log(person.toUpperCase()); // CHANNING TATUM
console.log(person); // channing tatum

person = 'channing'; // ❌ ERROR: cannot reassign const

String Keys and Indexing

const diet = 'food';

const alien = {
name: 'martian',
'age': 100, // `age: 100` is the same
'current-status': 'alive',
['home' + 'planet']: 'Mars', // `homeplanet: 'Mars'` is the same
['favorite' + diet]: 'pizza', // `favoritefood: 'pizza'` is the same
};

console.log(alien.name); // 'martian'
alien.name = 'martin';

console.log(alien['name']); // 'martin'
alien['name'] = 'allen';

console.log(alien['current-status']); // 'alive'
console.log(alien['favorite' + diet]); // 'pizza'

Number Keys

const digits = {
1: 'one',
dos: 'two',
3: 'three',
};

console.log(digits.dos); // 'two'
console.log(digits['dos']); // 'two'

console.log(digits[1]); // 'one'
console.log(digits['1']); // 'one'

digits[1] = 'uno';
console.log(digits[1], digits['1']); // 'uno', 'uno'
digits['1'] = 'ONE';
console.log(digits[1], digits['1']); // 'ONE', 'ONE'

Object Equality

const personA = { name: 'John Doe' };
const personB = { name: 'John Doe' };

console.log(personA === personB); // false

console.log(personA === personA); // true
console.log(personB === personB); // true

const personC = personA;

console.log(personC === personA); // true

personC.name = 'Jane Doe';
console.log(personA.name); // Jane Doe

Shorthand Structuring

Shorthand property

const make = 'Ford';
const model = 'Mustang';
const color = 'White';

let car;

car = {
make: make,
model: model,
color: color,
};

car = {
make,
model,
color,
};

Spread operator

const point2d = {
x: 0,
y: 0,
};

let point3d;

point3d = {
x: point2d.x,
y: point2d.y,
z: 0
};

point3d = {
...point2d,
z: 0,
};

Spread ordering

let taskPending = {
title: 'Record Tutorial',
when: 'Today',
isCompleted: false,
};
let taskCompleted;

taskCompleted = {
...taskPending,
isCompleted: true,
}; // { title: 'Record Tutorial', when: 'Today', isCompleted: true }

taskCompleted = {
isCompleted: true,
...taskPending,
}; // { title: 'Record Tutorial', when: 'Today', isCompleted: false }

Shorthand Destructuring

Basics

let point = { x: 0, y: 10, z: 20 };

{
const x = point.x, y = point.y;
}

{
const { x, y } = point;
}

{
const { x: pointX, y: pointY, z: pointZ } = point;
console.log(pointX, pointY, pointZ); // 0, 10, 20
}

{
const { x, ...rest } = point;
console.log(x, rest); // 0, { y: 10, z: 20 }
}

Nested Destructuring

let center = {
name: 'origin',
location: { x: 0, y: 0, z: 0 }
};

{
const { location: loc } = center;
console.log(loc); // { x: 0, y: 0, z: 0 }
}

{
const { location: { x } } = center;
console.log(x); // 0
}

typeof Operator

let point = { x: 0, y: 0 };
let person = { name: 'Jennifer' };

console.log(typeof point); // 'object'
console.log(typeof person); // 'object'

point = { type: 'point', x: 0, y: 0 };
person = { type: 'person', name: 'Jennifer' };

console.log(point.type); // 'point'
console.log(person.type); // 'person'

if (point.type === 'point') {
console.log('This is a point');
}

if (person.type === 'person') {
console.log('This is a person');
}

Additional Operators

Below example shows delete and in operators

const bird = {
type: 'chicken',
};

bird.name = 'liftoo';
console.log(bird); // { type: 'chicken', name: 'liftoo' }

bird.name = undefined;
console.log(bird); // { type: 'chicken', name: undefined }

console.log('name' in bird); // true

delete bird.name;
console.log(bird); // { type: 'chicken' }

console.log('name' in bird); // false

if ('type' in bird) { // true
console.log(bird.type); // 'chicken'
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Objects are one of the two key forms of containers for other data types that we have within JavaScript. A core part of being a successful JavaScript engineer is having mastery of how to use objects effectively and this tutorial is designed to do exactly that. So let's go at score. JavaScript objects are collections of properties where each property is a key value pair separated by commerce. Here we have a simple object specified by an object literal that contains a name property with the value of the string magic mic and a gender property with the value of the string male,

00:33

we can access the properties off of an object by using the documentation. For example, Channing name will give us a magic mic and we can even modify the values by doing an assignment statement. For example, assigning Channing name to the string Tatu will make Channing name equal to that string. Now if he assign to a property that isn't a part of the object right now magically that does get added as a property of the object. So now Channing has a new property with the key skill and a value of the string dance. Now we've actually been using string values, but you can actually use a value of any te type within JavaScript. For example,

01:09

we can create a new property born with the value in 1980, and objects can even have properties that are objects themselves. For example, now the key planet has the value of an object with name Earth. To access the properties off of an object contained within an object, you simply use the documentation as many times as you need. For example, to get the value of Earth's string, we need to go from Channing to planet to the planet's name. Now, after making all of these modifications, just as a quick recap, this is the current object that is contained within the Channing variable.

01:42

If we try to access a property that doesn't exist on the object, for example, hey, we are trying to access citizenship, the Jiao skip runtime returns. The special value that we've seen a few times before called undefined. Something that I often find beginners struggling with is the difference between an immutable reference and the mutable nature of an object. Objects within JavaScript are mutable references. What that means is that if we have a variable pointing to an object, in addition to using its keys to read the values, we can actually write to the key as well.

02:14

So if we modify the key name to point to a new string at tum, the object is going to get mutated. Now this is independent of the only guarantee that is offered by cons, which is that with a cons variable, you cannot do a reassignment. If the value that is contained by the const is immutable, you can of course mutate it. As we have done right now, the primitives that we've looked at within JavaScript are all immutable. So if you have a const person pointing to a string, even though there are methods on the string to return a new modified strings, the original string is always left unchanged and since with the cons and

02:49

assignment is not allowed, it is always going to be true. That person is going to be the string Channing Tatu. And as a side note, the silly mistake of trying to reassign a cons To a new value is always caught by transcript at compiled time. Keys and JavaScript objects are always strings, even though they look like identifiers. We can actually use any string that we like and there is a special syntax to allow you to create, read and write arbitrary string keys. Before we begin, let's just create a very simple variable called diet which points to the string food.

03:20

We create an object stored in a variable called alien with a property having the key name and the value string martian. In addition to having identifiers as keys, we can actually even use a string as a key. For example, have age as a key. Now this is going to be exactly the same as having an identifier age, so we don't necessarily need to code age, but the advantage of using quotes is that we can actually use any string over here, something that might not even be a valid identifier. For example, current status with a dash in between is not a valid identifier, but we can create it as a key by using quotes.

03:56

If you want to take it to the next level, we can actually even use square brackets around our keys and this actually allows us to use any JavaScript expression within the key name. And the final key will actually be the evaluation of that expression. For example, in this particular case, it is going to be the same as a key with the name home planet. The ability to use expressions means that we can even generate key names from other variables. For example, hey, we are generating the key name favorite food by using the diet variable. Now if you have a valid identifier for a key, we can use it with the standard.as we have been doing till right now.

04:30

But JavaScript objects also support the index notation that allows you to pass in a string expression. For example, for the name property, we can pass in the string name using the square bracket index notation. And of course the advantage of using the bracketed index notation is that we can pass in any string that we like, for example, strings with dashes inside of them or even calculate the string based on simple JavaScript expressions. For example, hey, we are accessing Ved food, which of course we previously initialized to Pisa. As you mentioned in previous lessons,

05:01

the interop between string and number in JavaScript is excellent and in fact it is so seamless that you can safely assume numbers as keys and objects even though they are still strings underneath. To demonstrate that, consider a very simple object called digits that has some keys as numbers and other keys as identifiers. Now we already know that using Doss as an identifier with the dot notation or using the square bracketed string index lookup, it is going to be the same property with number keys. We cannot actually use the documentation because of course numbers aren't valid identifiers within JavaScript. However,

05:37

we can use them with a square bracket lookup and it doesn't really matter if we pass in the number or the string version of the number, they are going to be exactly the same. And just like with reading where we can use a number or a string version of the number, we can actually write with a number or a string version as well. And the same underlying property is the one that gets modified. Unlike Primitives like number string and bullion equality on objects works by reference and not by value. So even though two objects might be completely equivalent structurally unless they point to the same reference, they will not be equal.

06:10

Consider two simple variables, person A and person B pointing to two different JavaScript objects which are both structurally equivalent. That is they both have the name property pointing to the string, John Doe. However, whenever we use an object lateral, we are creating a new distinct object as far as JavaScript is concerned. So person A will not be strictly equal to person B. Of course, person A will be equal to person A and person B will be equal to person B. Now if we create a new variable called person C and point it to the same object that is contained within person A, then in that particular case,

06:43

person C will be equal to person A because they are the same object literal and to further drive this point home, if you modify a property on person C because person A is a reference to the same object when we read the name for person A, we see the updated value of Jane Doe. Modern J Script comes with some pretty neat shorthand syntax that can help simplify how we create objects. Let's first focus on additional syntax for creating objects or structuring objects. And for that purpose we have three simple variables, make, model and color, and our objective is to create a car with all of these members. Now of course we can do it the way that we have been doing with key value pairs.

07:21

As an example. The key make points to the value of the variable make and so on. Now, if the identifier used for the key and the value are exactly the same, we can actually use a shorthand syntax where we do not need to specify the value and it's automatically assumed that the key is going to be make and the value is going to be whatever is contained by the identifier make. So the result of creating an object in either of these two ways is exactly the same. Another nice feature offered for creating objects within JavaScript is the spread operator consider a simple 0.2 D that has members X and Y, and we want to create a 0.3 D that has the same X and Y members along with the

07:56

additional Z member initialized to zero. Now we could totally list these numbers out and copy them over, but there is a shorter syntax known as the spread operator, which can be used to spread the key and the values of one object into another. So these two statements are equivalent. Point three D will have all of the properties of 0.2 D, which is X and Y along with this new property Z of zero. One thing to be aware of with the spread operator is that order is important. So here we have an object task pending that has title when and is completed and we want to create a new version of this object with is completed set to true.

08:32

Now, the right way to create this new object would be to take all of the properties of task pending, spread them in, and then overwrite the is completed property to be the value. True. If you were to reverse the order that is have is completed first and then replace all of the properties from task pending, then this is completed is actually going to get completely ignored as the task pending version of is completed. False is what's Going to win. As a side note, silly mistakes like this are caught by TypeScript, and here TypeScript is complaining that there is no point in providing this property as it'll always get replaced by the task pending version.

09:06

Now just like JavaScript has fancy syntax for putting stuff into objects that is structuring, it has fancy syntax options for pulling stuff out of objects as well, which in programming language terms is called destructuring. Consider a simple object containing X, Y and Z members. Now if you wanted to pull out the members x and Y from this object, we can do that by using point X and point point y, but as you can see there is a repetition of point tot between these two variables. We can actually use the shorthand destructuring syntax offered by JavaScript to pull out the members X and Y into their new variables by using a pattern.

09:44

Very similar to structuring on the left-hand side of the equals operator. These two statements are completely equivalent and as you can see, the Destructuring version is much nicer. Now within Destructuring there is a long form syntax as well that allows you to rename the value that you are reading. For example, here we are reading the values X, Y, and Z from point and then renaming them into local variables called point X, point Y, and point C. Now, just like there is a spread operator for structuring, there is a spread operator with the triple dots for destructuring as well. What this does is it takes all of the properties that haven't already been

10:21

structured and puts them into an object with a variable name of our choice. Here we are saying that takeout X and put it into the variable X and for everything else, Y and Z put them into a variable called rest. And if you want to really impress your colleagues, you can actually even use Destructuring within Destructuring. To demo this, we have a simple center object that has a name, property and a location property, which itself is an object containing members X, Y, and Z as we already know. We can pull out the member location from center and give it a local variable name called lock.

10:55

What we can even do at this point is that instead of using a local variable called lock, we can apply destructuring again to destructure that object and pull out any of its members. For example, hey, we are pulling out the member X from location. Even though JavaScript's type of operator does work on objects, it doesn't provide enough clues to disambiguate between different structures. So I definitely recommend using a discriminating field, commonly called type. Hey, we have two simple objects. One is of a type point and the other is of a type person. Now as far as JavaScript is concerned,

11:28

these are both JavaScript objects and with the type of operator on an object, JavaScript at runtime returns the string object. Clearly this is not enough information to discriminate between the different structures. So the recommendation here is to add another property to the individual objects. For example, HA adding a property called type, which is going to be 0.4 points and person for persons. And this will actually allow us to easily determine What kind of structure might be present within the different objects. Now this isn't really a JavaScript feature, this is mostly just clever programming,

12:00

but this is a pattern that is used commonly enough that it is worth knowing as a professional developer. JavaScript comes with delete and in operators that can be used to effectively manage and test for presence of properties on objects. For example, hey, we have a simple bird object that has a property type with a value chicken. Now as we know, we can add additional properties to the bird at any point. For example, we can set bird name to lift two, and now the bird will have two properties type chicken and name lift two. But what about removing properties from an object?

12:33

Now you might think that you can just set that property to the value undefined and that property will go away, but that will not be the case. The bird will still have the two properties, it's just that the second property value will be turned to undefined. And there is an operator within JavaScript called in which can be used to test the presence of a property on an object. And of course Bird still has the name property present. The proper way to get rid of a property from an object is to actually use another JavaScript operator called Delete. Here we have completed deleted the name property from Bird, and now of course when we log out Bird,

13:07

it has only one property with the key type and a value chicken. With this property deleted name and bird will return false and of course, type still exist in Bird and we can use that in an if condition. Clearly there is a lot of power and three sweet syntax baked into modern JavaScript objects and honestly that makes working with data quite enjoyable. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36