March 13th, 2020
Before we begin, I’d like to make sure you’ve checked out yesterday’s story. If you have, well done! Today we’ll be talking about objects! If you haven’t, feel free to check out yesterday's topic on the link below!
Javascript in 15 Days : Multidimensional Arrays
So, imagine you need to hold data for a student. This student has a name, gender, probably height (in this case, centimeters), and also date of birth (using format DD/MM/YY). Using what we've learned, you could probably think of two ways:
Now, you may think, oh I guess it's fine right? But what you may not know is that if there are big chunks of data being stores like this, let's say you took a break of maybe 2 days. Next thing you know, once you see this variable, you might not know what each element represents. Or even worse, a colleague doing a code review might not even know what these are. Luckily, Javascript has Objects.
Objects are a set of key and values in which you can store inside a variable, with each value being able to store any data type. Here's an example on how to declare a variable as an object, and how to print the object into the console.
Okay, so now you know how to declare an object, but what if you want to change the contents of it? Let's start with the simplest way, how do you print the name to the console?
Now, how about overwriting the height, to let's say 195?
Let's say you want delete the dateOfBirth
, you can simply use the delete
keyword!
Okay, now we've tried updating and deleting existing key and values, but what about adding new ones? And maybe even where the key contains space
?
Now that we can do all of that, let's integrate it simply with a loop, let's say you want to print each key and value pairs to the console, here's how you might do so.
Purpose: Returns an array with all the keys of the object.
Purpose: Returns an array with all the values of the object.
Purpose: Converts the object into a multidimensional array.
So, as you can see, you can do quite a lot of things with objects! Next up, we'll be discussing about Array Of Objects, the most interesting topic of this whole course! For now, be sure to practice a lot, and feel free to hit me up on Twitter or LinkedIn if you have any questions! Have a great day!