In the world of programming, JavaScript objects are like customizable containers where you can store different types of data in an organized manner. You can think of these objects as collections of 'properties'. Each property is a pairing of a unique key (like a label) and a value (the data you want to store under that label). This is similar to how a car can be characterized by its color, model, and manufacturer.
JavaScript objects are also known as dictionaries, and both terms are widely used. The analog with dictionaries comes from the fact that dictionaries also have words (keys) and their definitions (values).
There are a couple of ways to generate objects in JavaScript, but the most common one is via literal notation {}
. Here is an example:
As you can see, for each key-value pair, we put a <key>: <value>,
line in the object.
You can access data in objects using dot notation (object.property
) or bracket notation (object["property"]
). Here's an example:
Dot notation directly accesses properties, while bracket notation is useful for variables or keys containing special characters or spaces.
You can modify object values or add new properties by simply assigning a new value to the key:
In JavaScript, you can verify whether a key exists within an object by using the in
operator as shown below:
In this example, we inspect if the keys 'color'
and 'mileage'
are in the car
object. The expected outputs are true
and false
, respectively, since the car
object contains the 'color'
key but not the 'mileage'
key.
To delete properties from objects, use the delete
keyword, as shown in this example:
With the delete
keyword, the key-value pair completely disappears.
JavaScript provides several powerful methods to interact with objects. Key among them are Object.keys()
, Object.values()
, and Object.entries()
, which return arrays of an object's keys, values, and key-value pairs, respectively.
Let's demonstrate this with an example:
In the above code, Object.keys(car)
, Object.values(car)
, and Object.entries(car)
provide us with arrays containing the keys, values, and key-value pairs of the car
object, respectively.
Nested objects contain other objects, i.e., where the object's key contains a value that is also an object. Imagine the car
object housing a dimensions
object. Here's what it looks like:
As you can see, to access the nested property, we just applied the dot notation multiple times.
Bravo! You've mastered the basics of JavaScript objects, including nested objects. Now, brace yourself for exercises that align with these lessons. Hands-on practice solidifies learning and prepares you for future explorations. Let's move on to the application!
