4.4 Plain Objects - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v Michael>Next, we're going to take a look at</v> what are called plain objects in JavaScript. Objects have lots of different incarnations in JavaScript, and it can get a little confusing. We'll be talking a lot more about this in chapter seven, but for now, we're just gonna get a taste in the simplest possible context. The simplest version of objects, called plain objects as I just mentioned, can be thought of as key value pairs. In other languages, these are sometimes called hashes or associative arrays. So let's take a look at an example. Let's think about a user, say, in a hypothetical web application, and the user will start off as an empty object. So the way we indicate that is with curly braces like that. So we can roughly think of this kind of object as an array where the indices, instead of being integers like zero, one, two, three, are strings like this. So remember, we can access an array index using the square bracket notation. We can do the same thing here. So let's say the user's first name is my first name. That and the same thing for last name, just my last name. So now we can access these elements using the same notation. So if we wanna pull out the first name, we can just copy and paste this like that, like that. There's a second way of accessing these elements, which are called properties. That might sound familiar. Also called attributes. We can do this. Aha, first name, last name. This might look familiar. It's the same basic thing as this string property length. So we can access these using this notation, or we can use the dot notation that we've seen in a couple of other contexts. All right, so this sort of construction involves keys here, like first name and last name and values. Here's Michael and Hartl. It's worth noting that if you try to access a key that doesn't exist, JavaScript is actually fairly permissive. So some languages will raise an error if you try to do that. So if you look for a user of dude, that's undefined. You can also do this, and this can be useful if you're trying to see if an object has a particular key, because you can use a Boolean test. The Boolean value, as we've seen before, of undefined is just false. So finally, it's worth noting that we can just look at the raw object like that, and it is possible to define an object using this notation. So if we use other user, first name, and it works as expected.