Understanding JavaScript Objects

Understanding JavaScript Objects

A good understanding of Objects as a beginner will help you a lot if you are coding in JavaScript

Β·

7 min read

According to MDN Web Docs, JavaScript language itself is designed on a simple object-based paradigm, which means Objects hold immense significance here.

In this blog post, I'll try to explain JavaScript Objects and how they can be used, in a beginner-friendly manner.

Let's get started πŸŽ‰

GIF: Let's do this


What are Objects?

An object in JavaScript or any other language can be compared to the objects that we see in our day-to-day life. An Object is basically an entity with some set of properties that gives us a description of the object.

For example

  • A Pen is an object, the color of the ink inside is its property.
  • A Water Bottle is an object and the capacity, color, cap type are its properties.
  • A Human Being is an object, its weight, height, hair color, eye color are its properties.
  • A Book is an object, its author, publication, number of pages are its properties.
  • The device on which you are currently reading this blog, Mobile/Laptop is an object, its RAM, ROM, CPU type are its properties.

It's pretty simple, right? Next, we will see how can we declare these objects in JavaScript.


Creating Objects in JavaScript

An Object in JavaScript is declared just like any other variable, but using curly braces ({ }). And the properties that we discussed above are written in key and value pairs separated by a colon (key: value).

Let's see how we can declare the object pen, in JavaScript:

const pen = {
  inkColor: "blue"
}

Here, inkColor is the key and the string "blue" is its value.

Note: We can use any primitive data type (String, Number, Boolean, etc) or an Array[] or even a function to be stored as a value in an Object. When a function is a property of an object, it’s often called a method. Regarding the key part, JavaScript allows you to have both String and Number as an Object key, but it's advised to always use the String based keys. If you are not aware of all the primitive data types in JavaScript, you can read about it here and come back - MDN Web Docs

Now, for objects having more than one property all you need to do is separate those properties using a comma(,).

Now, Let's write other objects as well:

const waterBottle = {
  capacityInLitres: 1,
  color: "black",
  capType: "sipper"
}

const humanBeing = {
  heightInCm: 176,
  weightInKg: 89,
  hairColor: "black",
  eyeColor: "brown" 
}

const myBook = {
  author: "Atul Tameshwari",
  publication: "Web Development 101",
  pages: 209
}

const myDevice = {
  storage: 8/512,
  cpu: "Intel i5 10th Gen"
}

Now there's one thing to keep in mind, if you ever come across a condition where your property name contains a space in it, then you have to place it inside quotes.

Just like this:

const address = {
  "house no": 14,
  "colony name": "inoxe gardens"
}

Accessing Object Properties

To access the properties of an object, we use one of two notations: the dot notation and the array-like notation also called the bracket notation.

1. The Dot Notation

Below syntax illustrates the dot notation of accessing Object properties:

objectName.propertyName

Consider an example of the pen Object that we created above to understand this better

Let's say we want to check the color of the penthen:

const pen = {
  inkColor: "blue"
}

console.log(pen.inkColor)  
//-> blue

2. Array-like/Bracket Notation

Below syntax illustrates the array-like/bracket notation of accessing Object properties:

objectName.["propertyName"]

Consider an example of the myBook Object that we created above to understand this better

Let's say we want to check the author, publication and pages of the myBook then:

const myBook = {
  author: "Atul Tameshwari",
  publication: "Web Development 101",
  pages: 209
}

console.log(myBook["author"])  
//-> Atul Tameshwari
console.log(myBook["publication"])  
//-> Web Development 101
console.log(myBook["pages"])  
//-> 209

Updating Object Properties

Now we'll see how you can update the properties of an existing Object in JavaScript

1. Add New Property

Below are two approaches by which you can add a property to an existing object:

objectName.newProperty = "value";
// OR
objectName["anotherNewProperty"] = "anotherValue";

Let's say we have an Object blog and we want to update the object by adding followers and hostedOn as properties:

const blog = {
  name: "Web Development 101"
}

// adding a property
blog.followers = 6;

// also adding a property
blog["hostedOn"] = "Hashnode";

console.log(blog) 
//-> {name: "Web Development 101", followers: 6, hostedOn: "Hashnode"}

You can also use the same two approaches for updating the existing properties of an Object.

2. Delete Existing Property

JavaScript provides a delete operator to delete properties from an Object:

delete objectName.propertyName
// OR
delete objectName["anotherProperty"]

Let's say we want to update the humanBeing object by removing hairColor and eyeColor properties:

const humanBeing = {
  heightInCm: 176,
  weightInKg: 89,
  hairColor: "black",
  eyeColor: "brown" 
}

// deleting a property
delete humanBeing.hairColor

// also deleting a property
delete humanBeing["eyeColor"]

console.log(humanBeing)
//-> {heightInCm: 176, weightInKg: 89}

Some Useful JavaScript Object Methods

Below are some pre-defined Object Methods which you should know before working with Objects in JavaScript:

1. hasOwnProperty()

This method checks the object for the property which is given as the argument and then returns a boolean value.

objectName.hasOwnProperty("propertyName")

Let's create an object myDevices and then check it for some properties using the hasOwnProperty() method:

const myDevices = {
  laptop: "Asus Vivobook 14",
  mobile: "Redmi Note 7",
  headphone: "Boat Rockerz 500",
  earphone: "Boat Bassheads 225"
}

console.log(myDevices.hasOwnProperty("laptop"))
//-> true
console.log(myDevices.hasOwnProperty("earphone"))
//-> true
console.log(myDevices.hasOwnProperty("smart watch"))
//-> false
console.log(myDevices.hasOwnProperty("speaker"))
//-> false

Alternative in Operator

There's one more way of testing Objects for their properties and that is the in operator. The in operator also tests Objects for the given property and returns a boolean value.

propertyName in objectName

Let's check the above created myDevices object for its properties one more time, but this time using the in operator:

const myDevices = {
  laptop: "Asus Vivobook 14",
  mobile: "Redmi Note 7",
  headphone: "Boat Rockerz 500",
  earphone: "Boat Bassheads 225"
}

console.log("laptop" in myDevices)
//-> true
console.log("earphone" in myDevices)
// -> true
console.log("smart watch" in myDevices)
// -> false
console.log("speaker" in myDevices)
//-> false

2. Object.keys()

This method takes an Object as an argument and returns an array of all the property names or keys of the respective object.

Object.keys(objectName)

Taking the myDevices Object as an example, let's observe the output after passing the Object to the Object.keys() method:

const myDevices = {
  laptop: "Asus Vivobook 14",
  mobile: "Redmi Note 7",
  headphone: "Boat Rockerz 500",
  earphone: "Boat Bassheads 225"
}

console.log(Object.keys(myDevices))
//-> ['laptop', 'mobile', 'headphone', 'earphone']

3. Object.values()

This method takes an Object as an argument and returns an array of all the property values of the respective object.

Object.values(objectName)

Once again taking the myDevices Object as an example, let's observe the output after passing the Object to the Object.values() method:

const myDevices = {
  laptop: "Asus Vivobook 14",
  mobile: "Redmi Note 7",
  headphone: "Boat Rockerz 500",
  earphone: "Boat Bassheads 225"
}

console.log(Object.values(myDevices))
//-> [ 'Asus Vivobook 14', 'Redmi Note 7', 'Boat Rockerz 500', 'Boat Bassheads 225' ]

Iterating Over An Object

For iterating over all the properties of an object at once, we have the for...in loop:

for (let key in object) {
  // statements
}

Let's create an object superhero and iterate over its properties using for...in loop:

const superhero = {
  name: "Deadpool",
  universe: "MCU",
  costume: "Red & Black",
  carryGuns: true,
  carryShield: false
}

for (let key in superhero) {
  console.log(superhero[key])
}

The output in the console will look like this:

Deadpool
MCU
Red&Black
true
false

One thing to keep in mind

If you ever come across a situation where you need to access some Object's property but using a variable, then always remember that the Dot notation (.) will not work here. You should only use Array-like/Bracket Notation ([]) here.

When you're referencing a variable in the Bracket Notation, you need to skip the quote. That's kinda how you know you're dealing with a variable instead of accessing the property key.

Let's understand it using an example of fruitColor object:

const fruitColor = {
  red: ["Apples", "Cherries", "Strawberries"],
  green: ["Avacado", "Kiwi", "Limes"],
  yellow: ["Bananas", "Mangoes"]
}

const color = "red";

console.log(fruitColor.color)
//-> undefined
console.log(fruitColor[color])
//-> ['Apples', 'Cherries', 'Strawberries']

That's all folks!

GIF: Barak Obama drops mic

In JavaScript, objects are king. If you understand objects, you understand JavaScript.

Thank you'll for reading till the end πŸ˜ŒπŸ™Œ

And don't forget to follow me for more such blogs πŸ˜›


Help me buy some books? πŸ‘€