Understanding Objects in JavaScript
Mastering object methods, looping and difference between freeze and seal

In programming , We deal with real world entities. So there must be the way of storing the properties and its behaviors together . This facility is provide by the objects data structure.
It is defined as the collection of data by name- value pairs. It stores data in key-value pairs. The functionality is called the methods in objects.
Ways of creating Objects
There are various ways of creating objects in JavaScript. The mot used is Object literal . The ways are shown below .
// ways of creating objects
// 1. Object Literal {}
cost car = {
brand : "Toyota",
model : "Corolla"
}
// 2.new Object()
const carObj = new Object();
carObj.brand = "Toyota";
carObj.model = "Corolla";
//3.constructor function
function Car (brand, model) {
this.brand = brnd;
this.model = model;
}
const myCar = new Car("Toyota", "Corolla") ;
// 4.Es6+ class
class MyCar {
constructor(brand,model){
this.brand = brand ;
this.model = model ;
}
}
const anotherCar = MyCar("Tata", "Nexon")
Accessing Property
There are two ways to access property in object . by dot notation and square bracket . so What is difference between them know by following examples :
// Accessing property
const hero = {
name: "Luna the Brave",
class: "Mage",
level: 12,
health: 85,
mana: 120,
isAlive: true,
};
// get any property
console.log(hero.name) ;
console.log(hero.level) ;
// suppose you want to add property which has some space, symbol
// then we used bracket notation
hero["game-win"] = true ;
console.log(hero["game-win"]) ;
Adding and Deleting Property
It is easy to add property just by giving name and assign value and if any property need to delete do by using delete keyword.
hero.weapon = "fire";
console.log(hero.weapon) ;
// delete the property with delete keyword
delete hero.class
Checking property present in object
There are various ways to check the property is present or not in object .
// checking property is present or not
console.log(hero.mana !==undefined) // true means it is present
// if you access any property if not present it gives undefined
console.log(hero.power) // undefined
// There is good way to check by using in
console.log("power" in hero) // false
// one thing to keep in mind it also check in prototype like
console.log("toString" in hero) // true
// The best way to check only own property is hasOwnProperty
console.log(hero.hasOwnProperty("toString")) //false
Methods in Objects
Like Objects has methods in JavaScript. If anything has methods that are object in nature . So In JavaScript It is called everything is object under the hood .
There are Object.keys, Object.values and Object.entries . These are methods . It used for getting keys, values or entries of objects like
// methods in objects
const artifact = {
name: "Obsidian Crown",
era: "Ancient",
value: 50000,
material: "volcanic glass",
};
// What are the data type comes in using these methods
const keys = Object.keys(artifact)
console.log(keys)
// ['name', 'era', 'value', 'material']
// all keys in arrays
console.log(Array.isArray(keys)) // true
const values = Object.values(artifact) ;
console.log(values) ;
// ['Obsidian Crown', 'Ancient', 50000, 'volcanic glass']
// arrays of values
// getting entries
const entries = Object.entries(artifact) ;
console.log(entries) ;
// [Array(2), Array(2), Array(2), Array(2)]
// nested array with [[key1,value1], [key2,value2]]
Looping Through objects
We know Object is non iterable. It means we cannot directly use for of loop in objects . so we have to take help of these methods like Object.entries to get array and then loop through it .
// loop through it
for(let [key,value] of Object.entries(artifact)){
console.log(`\({key} : \){value}`)
}
// name : Obsidian Crown
// era : Ancient
// value : 50000
// material : volcanic glass
// there is one loop we can used in object which is
// for in loop
for(let key in artifact){
console.log(key)
console.log(artifact[key])
}
Suppose we need to convert nested array into object then we have methods that is Object.fromEntries() . It converts the output of entries back to object.
// there is array of nested array
const priceList = [
["Obsidian Crown", 50000],
["Ruby Pendant", 30000],
["Iron Shield", 5000],
];
const priceObj = Object.fromEntries(priceList) ;
console.log(priceObj) ;
// {Obsidian Crown: 50000, Ruby Pendant: 30000, Iron Shield: 5000}
Object.freeze and Object.seal
We know object are created and stored as reference in JavaScript . so It is mutable . We can add, delete and update the property of objects so We can Control it . We can freeze the entire object so It cannot get update, delete and add any new property in it .
The main difference between them is After the Object.freeze The Object becomes immutable means we can not change, add, delete the property but after Object.seal We can only change the existing property . The delete and addition is not allowed .
// concept of Object.freeze and Object.seal
const displayCase = {
artifact: "Obsidian",
location: "Hall A, Case 3",
locked: true,
};
// displayCase.locked = false
// console.log(displayCase) ;
// it get changed so
Object.freeze(displayCase) ;
displayCase.locked = false
console.log(displayCase) ;
// no change now
displayCase.version = "1.2.3" ;
console.log(displayCase)
// means after Object.freeze we cannot mutate the objects
// Object.seal
// it is the method which enable us to change only the existing property
const catalogEntry = {
id: "ART-001",
description: "Ancient Crows",
verified: true,
};
Object.seal(catalogEntry);
catalogEntry.verified = false ;
console.log(catalogEntry)
// it only change the existing property
catalogEntry.price = 200;
console.log(catalogEntry) ;
// no new property add
delete catalogEntry.id
console.log(catalogEntry)
// no delete property
Configuring the property
Sometimes we need to configure the property in object so that they can be loopable, writable or can delete .
// configuring the property
const secureArtificats = { name: "Ruby Pendant" };
Object.defineProperty(secureArtificats, "catalogId" , {
value:"SEC-999",
writable:true,
enumerable:false,
configurable:true ,
})
console.log(secureArtificats) ;
// {name: 'Ruby Pendant', catalogId: 'SEC-999'}
writable : It means the value of property can be change. if true then we can change the value otherwise not.
enumerable : it is for looping by using for of loop
configurable : If it is true then we can delete property and also redefine the attributes of like writable, enumerable if it is true .
// configuring the property
const secureArtificats = { name: "Ruby Pendant" };
Object.defineProperty(secureArtificats, "catelogId" , {
value:"SEC-999",
writable:false,
enumerable:false,
configurable:false ,
})
// console.log(secureArtificats) ;
// {name: 'Ruby Pendant', catalogId: 'SEC-999'}
console.log(secureArtificats.catelogId);
secureArtificats.catelogId = "HACKED";
console.log(secureArtificats.catelogId);
for (const [key, value] of Object.entries(secureArtificats)) {
// only print the property which is emunerable
console.log(`\({key} : \){value}`);
}
// SEC-999
// SEC-999
// name : Ruby Pendant
// to check property is dexcription
// we have getOwnPropertyDescriptor
console.log(Object.getOwnPropertyDescriptor(secureArtificats, "name"))
// {value: 'Ruby Pendant', writable: true, enumerable: true, configurable: true
Difference between object and array
The main difference is the way of storing data . In objects we store in key value pair. but in array we just give name . In array there we get indexing starting from 0 . we have length property but i n object there is no such property and all keys are either string or Symbol.
There is one thing when we give numbers as key in object then JavaScript sorted it in run time.
const obj = {
5:"chocolate",
20:"noodles",
10:"Chips",
2:"Nothing"
}
console.log(obj)
//{2: 'Nothing', 5: 'chocolate', 10: 'Chips', 20: 'noodles'}
Summary
This is all about object in JavaScript. It store data in name value pair. It is very easy to create and used in our program .



