Day 8/100 of JavaScript 🚀 Today’s Topic: Objects and their manipulation Objects in JavaScript store data in key-value pairs Example: const user = { name: "Apsar", age: 24 }; 🔹Accessing values user.name user["age"] 🔹Adding / updating user.city = "Chennai"; user.age = 25; 🔹Deleting delete user.city; 🔹Iteration for (let key in user) { console.log(key, user[key]); } 🔹Useful methods Object.keys(user); Object.values(user); Object.entries(user); 🔹Copy (shallow) const newUser = { ...user }; 🔹Object.freeze() Object.freeze(user); user.age = 30; // ❌ no change Prevents adding, deleting, or updating properties 🔹Object.seal() Object.seal(user); user.age = 30; // ✅ allowed user.city = "Chennai"; // ❌ not allowed Allows update, but prevents add/delete 🔹Object.assign() const obj = Object.assign({}, user); Used to copy or merge objects Objects are reference types. Methods like "freeze" and "seal" help control how data can be modified #Day8 #JavaScript #100DaysOfCode
JavaScript Objects and Key-Value Pairs Manipulation
More Relevant Posts
-
🧠 Day 28 — WeakMap & WeakSet in JavaScript (Simplified) You’ve seen Map & Set — now let’s look at their smarter versions 👀 --- 🔍 What makes them “Weak”? 👉 They hold weak references to objects 👉 If the object is removed, it can be garbage collected automatically --- ⚡ 1. WeakMap 👉 Key-value pairs (like Map) 👉 Keys must be objects only let obj = { name: "John" }; const weakMap = new WeakMap(); weakMap.set(obj, "data"); console.log(weakMap.get(obj)); // data --- ⚠️ Important ❌ Keys must be objects ❌ Not iterable (no loop) ❌ No size property --- ⚡ 2. WeakSet 👉 Collection of unique objects let obj1 = { id: 1 }; const weakSet = new WeakSet(); weakSet.add(obj1); console.log(weakSet.has(obj1)); // true --- 🧠 Why use them? 👉 Helps with memory management 👉 Avoids memory leaks 👉 Used internally in frameworks --- 🚀 Real-world use ✔ Caching objects temporarily ✔ Tracking object references ✔ Managing private data --- 💡 One-line takeaway: 👉 “WeakMap & WeakSet allow objects to be garbage collected automatically.” --- If you want to go deeper into JavaScript internals, this is a great concept. #JavaScript #WeakMap #WeakSet #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🔑 JavaScript Set Methods – Quick Guide 1. Creation const letters = new Set(["a","b","c"]); // from array const letters = new Set(); // empty letters.add("a"); // add values 2. Core Methods MethodPurposeExampleReturns add(value)Add unique valueletters.add("d")Updated Set delete(value)Remove valueletters.delete("a")Boolean clear()Remove all valuesletters.clear()Empty Set has(value)Check existenceletters.has("b")true/false sizeCount elementsletters.sizeNumber 3. Iteration Methods MethodPurposeExample forEach(callback)Run function for each valueletters.forEach(v => console.log(v)) values()Iterator of valuesfor (const v of letters.values()) {} keys()Same as values() (compatibility with Maps)letters.keys() entries()Iterator of [value, value] pairsletters.entries() 4. Key Notes Unique values only → duplicates ignored. Insertion order preserved. typeof set → "object". set instanceof Set → true. 📝 Exercise Answer Which method checks if a Set contains a specified value? 👉 Correct answer: has() 🎯 Memory Hooks Set = Unique Collection Think: “No duplicates, only distinct members.” add to insert, has to check, delete to remove, clear to reset.
To view or add a comment, sign in
-
Recently spent some time revisiting JavaScript fundamentals — especially arrays and objects — and it’s a reminder of how powerful these core methods really are 👇 🔹 map() – transform data const prices = [100, 200, 300] const discounted = prices.map(p => p * 0.9) → [90, 180, 270] 🔹 filter() – pick what you need const users = [{active: true}, {active: false}] const activeUsers = users.filter(u => u.active) 🔹 reduce() – compute totals const cart = [50, 30, 20] const total = cart.reduce((sum, item) => sum + item, 0) → 100 🔹 find() – get first match const products = [{id: 1}, {id: 2}] const item = products.find(p => p.id === 2) 🔹 some() – check if any match const hasExpensive = prices.some(p => p > 250) 🔹 every() – check if all match const allPositive = prices.every(p => p > 0) 🔹 includes() – simple existence check const tags = ["js", "react"] tags.includes("js") // true 🔹 flat() – flatten arrays const nested = [1, [2, 3], [4]] const flatArr = nested.flat() → [1, 2, 3, 4] 🔹 sort() – order data const nums = [3, 1, 2] nums.sort((a, b) => a - b) → [1, 2, 3] 🔹 Object destructuring const user = { name: "Alex", role: "Admin" } const { name, role } = user 🔹 Spread operator const updatedUser = { ...user, role: "Super Admin" } 💡 Takeaways: • Strong fundamentals = cleaner and more readable code • Array methods can replace complex loops • Better understanding = faster debugging Sometimes improving as a developer is just about going deeper into the basics. #JavaScript #WebDevelopment #Coding #Developers
To view or add a comment, sign in
-
🚀 Harness the Power of Arrays in JavaScript! 🚀 Arrays are like containers that hold multiple values in a single variable, making data organization and manipulation a breeze in JavaScript. For developers, mastering arrays is crucial for efficient data handling and accessing elements for various operations. Here's a simple breakdown to work with arrays: 1️⃣ Declare an array using square brackets: let myArray = [value1, value2, value3]; 2️⃣ Access elements using their index: let thirdElement = myArray[2]; 3️⃣ Add elements using push() method: myArray.push(value4); 4️⃣ Remove elements using pop() method: myArray.pop(); Full code example: ```javascript let myArray = ["apple", "banana", "orange"]; let thirdElement = myArray[2]; myArray.push("grape"); myArray.pop(); ``` Pro tip: Use array methods like map(), filter(), and reduce() for advanced data manipulation tasks efficiently. 🌟 Common mistake to avoid: Forgetting that array indexes start from 0, so the first element is always accessed as myArray[0]. Let's hear from you: What's your favorite array manipulation method in JavaScript? 🤔 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaScript #Arrays #DataManipulation #CodeNewbie #WebDevelopment #ProTip #DevTips #CodingIsFun
To view or add a comment, sign in
-
-
Most JavaScript devs think Object keys follow insertion order. And it’s caught even senior devs off guard. Create an object and add keys in this order: "b", "a", "1". const obj = {}; obj.b = 'second'; obj.a = 'third'; obj.1 = 'first'; Log Object.keys(obj). You’d expect: ['b', 'a', '1'] You get: ['1', 'b', 'a'] 🤯 The number jumped to the front, but the strings stayed in order. Same object. Same assignment logic. Completely unexpected order. This silently breaks: → API wrappers that expect keys to match a specific schema → UI components that map over objects for "alphabetical" sorting → Testing suites that compare object snapshots No error thrown. Just a data structure that "rearranges" itself. Why does this happen? It’s defined in the ECMAScript spec (OrdinaryOwnPropertyKeys). JavaScript objects don't have a single "order." They follow a strict three-tier hierarchy: 1. Integer Indices: Sorted in ascending numeric order (always first). 2. String Keys: Sorted in chronological insertion order. 3. Symbol Keys: Sorted in chronological insertion order (always last). The engine treats "1" as an integer index, so it "cuts the line" and moves to the very front, regardless of when you added it. Once you know this, you'll stop trusting Object.keys() for ordered data and start reaching for Map. 🔖 Learn more about how JS engines handle property order → https://lnkd.in/gRY6hdcM Were you aware that numbers always "cut the line" in JS objects? 1️⃣ Yes / 2️⃣ No 👇 #JavaScript #WebDev #Coding #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
🚀 Exploring Blog 9 of the JS series: Map and Set in JavaScript. While developers often rely on objects and arrays, there are specific scenarios where Maps and Sets offer distinct advantages. Understanding when to use these data structures can enhance your coding practices. For insights into these use cases, check out the short blog linked below. Blog link: https://lnkd.in/gWRsZxy6 Hitesh Choudhary Piyush Garg Chai Aur Code #webdevcohort2026 #javascript #jsdatatypes
To view or add a comment, sign in
-
Day 23/100 of JavaScript Today’s topic : "this" keyword "this" refers to the object that is currently executing the function But its value depends on how the function is called, not where it is written 🔹In object method const user = { name: "Apsar", greet() { console.log(this.name); } }; user.greet(); // Apsar 🔹In regular function function show() { console.log(this); } show(); // global object (or undefined in strict mode) 🔹Arrow function const obj = { name: "Apsar", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own "this", they inherit it 🔹call, apply, bind function greet() { console.log(this.name); } const user = { name: "Apsar" }; greet.call(user); #Day23 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
🧠 Day 27 — Set & Map in JavaScript (Simplified) JavaScript gives you more than just arrays & objects — meet Set and Map 🚀 --- ⚡ 1. Set 👉 A collection of unique values const set = new Set([1, 2, 2, 3]); console.log(set); // {1, 2, 3} --- 🔧 Common Methods set.add(4); set.has(2); // true set.delete(1); 👉 Perfect for removing duplicates --- ⚡ 2. Map 👉 Stores key-value pairs (like objects, but better in some cases) const map = new Map(); map.set("name", "John"); map.set(1, "Number key"); console.log(map.get("name")); // John --- 🧠 Why Map over Object? ✔ Keys can be any type (not just strings) ✔ Maintains insertion order ✔ Better performance in some cases --- 🚀 Why it matters ✔ Cleaner data handling ✔ Useful in real-world apps ✔ Avoid common object limitations --- 💡 One-line takeaway: 👉 “Set handles unique values, Map handles flexible key-value pairs.” --- Once you start using these, your data handling becomes much more powerful. #JavaScript #Set #Map #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🚀 Memory Management & Garbage Collection in JavaScript — Explained Simply Ever wondered how JavaScript handles memory without manual control? 🤔 👉 Unlike languages like C/C++, JS manages memory automatically 🧩 What is Memory Management? 👉 Process of: • Allocating memory • Using memory • Releasing memory ✔ All handled automatically by JavaScript engine ⚙️ How It Works 1️⃣ Allocation → Memory is created when you declare variables 2️⃣ Usage → You read/write data 3️⃣ Release → Memory is freed when no longer needed 🧠 What is Garbage Collection (GC)? 👉 Process of removing unused memory ✔ Runs automatically in background ✔ Prevents memory leaks 🔍 How GC Decides What to Remove 👉 Uses Mark & Sweep Algorithm • Mark → Find reachable objects • Sweep → Remove unreachable ones ⚡ Key Concept ✔ Objects referenced → kept in memory ❌ Objects not referenced → removed ⚠️ Common Memory Leaks (Real-world) ❌ Global variables ❌ Unremoved event listeners ❌ setInterval / setTimeout not cleared ❌ Closures holding large data ❌ Detached DOM elements 🧠 React-Specific Example useEffect(() => { const interval = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(interval); // cleanup }, []); 👉 Without cleanup → memory leak ❌ ⚡ Best Practices ✔ Clean up effects (`useEffect`) ✔ Avoid unnecessary global variables ✔ Remove event listeners ✔ Use WeakMap / WeakSet when needed ✔ Keep references minimal 🔥 Real Impact ✔ Better performance ✔ Avoid crashes ✔ Stable applications 🧠 Simple Way to Understand • Referenced → stays in memory ✅ • Not referenced → garbage collected ❌ 💬 Have you ever debugged a memory leak in your app? #JavaScript #React #WebDevelopment #Frontend #Performance #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
⚡15 JavaScript Senior level questions about objects: 1) How do property descriptors work, and how do get/set interact with writable/configurable/enumerable? 2) Walk through the [[Get]] and [[Set]] algorithm (prototype chain, shadowing, strict mode) 3) What’s the difference between in, hasOwnProperty, and Object.hasOwn? When is Object.hasOwn preferable? 4) Explain Object.create(null) and when you’d use it over {}. 5) this binding in object methods, method extraction, and arrow pitfalls 6) Enumerability, reflection, and key order: for…in vs Object.keys vs Object.getOwnPropertyNames vs Reflect.ownKeys 7) Deep copy strategies: structuredClone, JSON, spread, and Object.assign 8) Freezing, sealing, and extensibility: semantics and pitfalls 9) Proxies, invariants, and why Reflect is your friend 10) Symbols and well-known symbols: make plain objects iterable & controllable 11) Class fields and private fields: what are they actually? 12) super, [[HomeObject]], and why copying methods can break super 13) JSON serialization edge cases: toJSON, replacers, and lost values 14) Property definition vs assignment: descriptors, accessors, and side effects 15) Objects vs Map/WeakMap: key types, iteration, GC, and performance #JavaScript #TechInterview
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development