Like A Girl

Pushing the conversation on gender equality.

Code Like A Girl

Getting a handle on Objects in JavaScript

*This post belongs to my ‘Pre-Job Series’ — for more info, check it out here*

So this is another of those posts, that I started writing a long, long time ago and the reason it didn’t get written at the time was because at that point, I was totally unaware of Git and didn’t know how to write a gist (if this is also you, I eventually found this out and shared it here).

When I started learning about Objects in JavaScript, it seemed like a piece of cake at first but then it all fell apart when I tried to actually build something using them and I think this was because I got myself muddled with the different ways of defining them. So in keeping with the philosophy of the Pre-Job Series, this post is going to be a reminder to myself and anyone else who’s watching what this should look like.

The first way of doing this is called object literal notation and this is how it goes:

You can also define objects using dot notation and bracket notation. This is what dot notation looks like:

This is what bracket notation looks like:

In fairness, the last two examples are just ever so slightly misleading. You will notice that in my first example, I created the whole object with all the properties inside it, while in the next two, I created an empty object first, before essentially setting the properties on them. Being able to do this is useful because it means you can add to objects after having created them. Note that even when you create an object using literal notation, you can still add to it later using dot or bracket notation.

By the by, you can also use the syntax:

const elizabeth = new Object();

to create your objects, followed by setting the properties with dot or bracket notation.

And finally, in order to access the properties on your lovely new objects…it’s dot and bracket notation again!

And that’s it!