Objects
Now we'll dive into a bit more advanced data structures, objects! An object is like an array, except it uses curly brackets { } instead of square brackets [ ]— but most importantly, objects also differ in that they store values with keys, and can accept several data types. An object can be highly versatile, and can not only be used for data storage, but for more complex algorithms like hashmaps, which we'll go over later. Most interestingly, we can have objects with objects within them, and even arrays as well! It's important to mention that keys and values have a colon ' : ' separator between them.
Here's a simple example of an object:
let thisIsMyObject = {name: "John", age: 22};
In arrays, we used a process called indexing, and the index notation format to access values, eg; myArray[3]. With objects, we use a similar process called key access, and the key notation format to access values.
The main difference is that we use keys, instead of solely integers that refer to position, to select values from an object— and not to confuse you, but a key in an object can also be an integer =).
For example, in thisIsMyObject above, you'll see the value "John" belongs to the key, "name". As well as the value 22, belongs to the key, "age". This is what key notation would look like for accessing a value for a specific key in an object:
let nameValue = thisIsMyObject['name'];
console.log(nameValue);
# Output: "John"
Try printing the "age" value in the code editor below:
let ageValue = thisIsMyObject['age'];
console.log(ageValue);
# Output: 22
Now we'll look over a more intricate object, that's a bit larger and complex.
thisIsMyObject = {name: "John", age: 22, likes: ["Exercise", "Cooking", "Coding"]};
We see something in this object that we haven't seen before, an array as the value to a key. Let's try accessing the 1st index of John's likes using a mix of key notation and index notation!
let likes = thisIsMyObject['likes'];
console.log(likes);
# Output:# ["Exercise", "Cooking", "Coding"]
let likesFirstIndex = likes[1];
console.log(likesFirstIndex);
# Output:# "Cooking"