Mastering Objects in JavaScript Programming

Mastering Objects in JavaScript Programming

What are Objects?

  • Versatile and powerful

  • Collection of key and value pairs

Key and Value
Keys are unique identifiers also known as property name and the values can be of any type [string, boolean, integer, function or objects]
  • Mutable in nature

  • Access using Dot notation

  • Providing a flexible and dynamic way to store and manipulate the data.

  • Allow to group related data and behaviors together.

  • Objects can be created by using object literal {} or by constructor Object()

// using object literals
const abc = {
    name : "mohit",
    section : "B",
    "Blood Group" : "B+" //use double-quotes if the key has space between.
}
// Object constructor

const abc = new Object();
// store keys and values
abc.name = "mohit";
abc.section = "B";
abc.["Blood Group"] = "B+" // use brackets if the key has space between

Access Object properties using Dot Notation

Very common and simple way to access the object properties

// Create Object using object literals
const obj = {
    name : "raj",
    section : "C",
}

// access the value of specific key 
console.log(obj.name) // output: raj

// modify the value of a specific key
obj.name = "Rajesh"
console.log(obj.name) // output : Rajesh

Access Object properties using Bracket Notation

They are useful when a property name contains special character or are dynamic.

// consider the above object.

// access the value of a specific key
console.log(obj["name"]) // output :- raj

// access the value after storing in variable
const key = "section"
console.log(obj[key]) // output :- C

Iterating over object properties

Object is a constructor and it provides same functionality to all JavaScript objects.

To get an array of keys from the object

// consider the same object

console.log(Object.keys(obj)) // [ 'name', 'section' ]

To get an array of values from the object

// consider the same object

console.log(Object.values(obj)) // [ 'raj', 'C' ]

To get the combination of all keys and elements

// consider the same object

console.log(Object.entries(obj)) 
// [ [ 'name', 'raj' ], [ 'section', 'C' ] ]

Adding and Removing Object items

// to add an entry
obj.number = 2584785996

// to delete an entry
delete obj.section;

console.log(Object.entries(obj))
//  output :- [ [ 'name', 'raj' ], [ 'number', 2584785996 ] ]

Object with methods, prototype, inheritance and loop in objects are also there, I am not skipping them all but it would be better and comfortable if discussed them when we reach to that topic. If you want more such content then make sure to following me on all available platform

Instagram

LinkedIn

Hashnode


Thank you for reading 🤍

Written By Mohit Soni