Mastering JavaScript Objects: A Quick Deep Dive

𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐎𝐛𝐣𝐞𝐜𝐭𝐬 — 𝐀 𝐐𝐮𝐢𝐜𝐤 𝐃𝐞𝐞𝐩 𝐃𝐢𝐯𝐞 Objects are everywhere in JavaScript — whether you’re building APIs, handling data, or working with classes, they form the foundation of how JS works. 𝐂𝐫𝐞𝐚𝐭𝐢𝐧𝐠 𝐎𝐛𝐣𝐞𝐜𝐭𝐬 // Literal const person = { name: "Vedanti", age: 13, isDev: true }; // Constructor const car = new Object(); car.brand = "Toyota"; // Function constructor function Person(name, age) {  this.name = name;  this.age = age; } const p1 = new Person("Ananya", 24); // ES6 Class class PersonClass {  constructor(name, age) {   this.name = name;   this.age = age;  } } const p2 = new PersonClass("Ravi", 25); 𝐀𝐜𝐜𝐞𝐬𝐬𝐢𝐧𝐠, 𝐔𝐩𝐝𝐚𝐭𝐢𝐧𝐠 & 𝐃𝐞𝐥𝐞𝐭𝐢𝐧𝐠 console.log(person.name);    // Dot notation console.log(person["age"]);   // Bracket notation person.name = "Riya";      // Update delete person.age;       // Delete 𝐋𝐨𝐨𝐩𝐢𝐧𝐠 & 𝐔𝐭𝐢𝐥𝐢𝐭𝐢𝐞𝐬 for (let key in person) console.log(key, person[key]); Object.keys(person);  // ['name', 'isDev'] Object.values(person); // ['Riya', true] Object.entries(person); // [['name', 'Riya'], ['isDev', true]] 𝐎𝐛𝐣𝐞𝐜𝐭 𝐌𝐞𝐭𝐡𝐨𝐝𝐬 Object.assign({ a: 1 }, { b: 2 }); // Merge Object.freeze({ name: "Ananya" }); // Immutable Object.seal({ name: "Riya" });   // Can modify, not add/remove const proto = { greet() { console.log("Hi"); } }; const obj = Object.create(proto); obj.greet(); // Inherits greet 𝐃𝐞𝐬𝐭𝐫𝐮𝐜𝐭𝐮𝐫𝐢𝐧𝐠, 𝐒𝐩𝐫𝐞𝐚𝐝 & 𝐑𝐞𝐬𝐭 const user = { name: "Ananya", age: 24 }; const { name, age } = user;       // Destructure const user2 = { ...user, city: "Delhi" } // Spread const { name: n, ...rest } = user;    // Rest 𝐎𝐩𝐭𝐢𝐨𝐧𝐚𝐥 𝐂𝐡𝐚𝐢𝐧𝐢𝐧𝐠 & 𝐍𝐮𝐥𝐥𝐢𝐬𝐡 𝐂𝐨𝐚𝐥𝐞𝐬𝐜𝐢𝐧𝐠 const user3 = { address: { city: "Delhi" } }; console.log(user3?.address?.city);  // "Delhi" console.log(user3.name ?? "Guest"); // "Guest" 𝐂𝐨𝐧𝐯𝐞𝐫𝐭 𝐎𝐛𝐣𝐞𝐜𝐭 ↔ 𝐀𝐫𝐫𝐚𝐲 const sample = { x: 1, y: 2 }; const entries = Object.entries(sample);   // [['x',1],['y',2]] const backToObj = Object.fromEntries(entries); // { x:1, y:2 } Objects can be created, cloned, merged, frozen, or restructured — that’s what makes JavaScript so flexible. #JavaScript #WebDevelopment #Coding #LearnToCode #100DaysOfCode #DevCommunity

To view or add a comment, sign in

Explore content categories