Object Literals in JavaScript

Object Literals in JavaScript

·

2 min read

Table of contents

No heading

No headings in the article.

Object is an entity which has key-value pair or which has some properties and methods. Object Literal is a list of zero or more pairs of property key name and associated values enclosed in curly braces {}. In other words, object literals encapsulate the information in small packages. Btw, have you seen the grocery list which has names and quantities mentioned on it?? That's what an object literal is!!

Let's understand this with the same example;

// empty object literal
var grocery1 = {};

// object literal with key-value pairs
var grocery2 = {
    cucumber: "2kg",
    mango: "1kg",
    milk: "1 liter",
    meat: "1 packet"
};

In the above example, grocery2 is an object literal that encapsulates the information of grocery2. So inconclusion, Object Literal is a type of value (we call it object value) in JavaScript that contains references to other values (which are key-value pairs). One more point to note about it is, cucumber, mango, milk, meat, these are the properties of grocery2, they can't be changed from outside since they are scoped inside the object but their values can be changed since they are not scoped inside the object.

var grocery2 = {
    cucumber: "2kg",
    mango: "1kg",
    milk: "1 liter",
    meat: "1 packet"
};

grocery2.mango = "5kg"
console.log(grocery2)

//the output is 
{ cucumber: '2kg', mango: '5kg', milk: '1 liter', meat: '1 packet' }

In above example, the value of mango has been changed to 5kg but there is no possibility to change the key mango.