Object literals in JavaScript

Hi everyone, if you are reading this then that is awesome! So, I am Sagar, a tech enthusiast and I am here to share and document my web development journey.

In, today's article, I will share what I learned about Object literals in javascript. I found them a very cool and useful tool.

Now, what are Object literals?

Object literals are a collection of key-value pairs.

{name: value} pairs

Essentially, it is a collection of associations between a name (or key) and a value. The value can be a number, a string, an array, a function, or even another object. If the value is a function then it is known as a method.

Syntax of creating an Object:

we can create an object in javascript simply by:

let person = {
name: value,
name: value,
name: value
}
//here person is the name of your object literal, you can give it any valid name

An example of this is, Here we are creating an object named student to store student details and we can access those details ( values ) with the help of keys ( names ) associated with the values.

That's why it is called collection of key-value pairs lol***. I am a genius :)***

//here we are creating an object to store a student details.
let student = {
address: "B5 64 NewYork Street",
name: "Rahul",
gender: "Male",
city: "New Delhi",
age: 25
}

If you look at the above example, there is no order or sequence to the key-value pairs. We can access anything without the need to specify its position.

This is a major difference between an array and an object in javascript.

how to access these values?

The above two methods are how we can access the object literals :)

Let's dive into each:

First Method

  •   let student = {
      address: "B5 64 NewYork Street",
      name: "Rahul",
      gender: "Male",
      city: "New Delhi",
      age: 25
      }
    
      //lets access the name of this object 'student'
    
      console.log(student.name);  //==> Rahul
    

Second Method

let student = {
address: "B5 64 NewYork Street",
name: "Rahul",
gender: "Male",
city: "New Delhi",
age: 25
}

console.log(student['name']);   //==> Rahul
console.log(student['gender']);  //==> Male

That's it guys, But to be honest, these objects come in very handy for example, you can create an object of arrays or an array of objects. Most of the time these two come hand in hand and create a powerful combo (KAMEHAMEHA!!!) LOL

Object literals are fundamentals of javascript and that's what I learned and shared with you all. See you guys on the next blog ;)

Thanking You ( lol the habit of writing letters in school )

Yours faithfully lmao

Keep providing support and keep coding