Objects in JavaScript..30daysofjavascript => Day 7

Olajide Blessing Niniola
3 min readMar 24, 2021

Objects are values that contain a set of other values and just like variables they use keys to name their values.

JavaScript objects

Now wait a minute, this looks like arrays!!! There we go again with things looking like each other in programming. Well, it is quite simple, objects are used to give more details about a variable. For instance; a bag could have the name Hermes, a size 15inches and the colour red that is an object and a bag can have the items: phone, lip gloss, book and a pen.

Getting Keys

Getting object keys can be done in two ways.

  • Dot Notation: This is done by adding a dot before the name of the key
dot notation in objects
  • Bracket Notation: You can do this by putting the name of the key in a string inside a [] bracket. Note: The string is very important
Bracket Notation

Setting Keys

Overwriting or adding keys is easy, you can do this either by dot notation or bracket notation. Use dot notation with the name of the key after a dot and an equals sign or can use the bracket notation with the name of the key inside a string inside square brackets [“].

Setting keys in objects

Object Methods

Methods are operations or actions performed on objects. Methods are stored in properties as function definitions which means you have a function that performs an operation in an object.

Now if you noticed we did not say console.log(bookNameAndAuthor);. Because this will only give us a raw form of our code(i.e. the function codes, try this yourself) and not the desired result which is ‘Things falls apart by Chinua Achebe’, therefore objects methods are accessed using the syntax objectName.methodName(). What's also new in the above code snippet? the this keyword, this refers to the owner of the method. We can as well get our values by using console.log(bookDetails.name); but this already refers to the owners object. Asides from object methods, this can also be used in various ways. Read more about this keyword here.

object methods

I had a little bit of an issue writing this code to the log, that is why I have written another example. The snippet above gives an example of how to get results for more than one object.

What to remember

Objects can be displayed in the following ways:

  • Displaying the Object Properties by name
  • Displaying the Object Properties in a Loop
  • Displaying the Object using Object.values()
  • Displaying the Object using JSON.stringify()

Learn more here.

--

--