JavaScript objects
collections of properties and values (the "nouns")
So far, we have:
done some stuff with basic data values called primitives
assigned those primitives to locations called variables
done things to those variables with operators
done even more things to variables with functions
Now, we take it to another level with objects:
which encapsulate data in pairs called keys and values
the key describes the value
the value acts as the data point
could consist of a primitive, another object or even a function
Some (abstract and concrete) examples of objects:
We can gather from the above that:
the object has keys separated by commas
keys can have names similar to variables
but with no declaration keywords (i.e.
const
,let
,var
)
More abstractly:
Recall that objects copy by reference :
when we copy an object and we change the original...
... we also make the same changes in the copy!
... because variables store references to the object
...and not the object itself
Accessing object properties
Let's look at our abstract example of a complex object, with an additional key:
To access an object property, we can use the following notations (whether in a variable or passing it as an argument with console.log
):
dot notation
i.e.
complexObject.key2
to get"Hey"
bracket notation
i.e.
complexObject["multi-word key"]
to get"yes we can do this too"
this allows the key to have more than one word (however, the key name must use quotation marks) or even with variable names
For nested objects, for whichever notation, we can chain the properties:
This can go down to any number of levels, as both notations are robust but concise!
Removing object properties
We can use the unary delete
operator with the object's name and property:
To delete multiple properties at a time, we can use destructuring! In the next example, suppose we wish to remove key1
and key2
:
We would thus specify the properties that we wish to remove. Then, we use the spread operator to create a new object. Although this does not change the original object, it gives us an object with the removed properties.
Checking object properties : hasOwnProperty()
and in
hasOwnProperty()
and in
To check if a property name exists in an object, we can use a simple built-in method called hasOwnProperty():
We can also use the in
operator if hasOwnProperty()
is too long:
Optional chaining operator
We can use the optional chaining operator (a question mark, ?
, after the property name) to avoid worrying about whether or not an object or a property exists:
In the case above, key5
as a property does not exist but will not throw an error. Instead, it will return undefined
which we can handle accordingly.
Destructuring properties from nested objects
We can access the value of a "nested property within a property" (key2a
and key2b
in the example below) using a special destructuring syntax:
Last updated