🚀 #8 Why JavaScript Introduced Map (When Object Already Exists?) Today I explored the difference between Object and Map, and it finally clicked — Map isn't just another option… it's a smarter solution for key-value storage. 👇 ❌ The Limitations of Object Objects work fine for simple structured data, but they come with serious drawbacks when used as key-value stores: 🔸 Keys can only be strings or symbols — numbers, objects, or functions get converted to strings. 🔸 Insertion order isn’t guaranteed (especially in larger operations). 🔸 Risk of prototype pollution — built-in methods like toString or hasOwnProperty may be overwritten. 🔸 No direct size property → you must do Object.keys(obj).length. 🔸 Not performance-optimized for frequent add/remove operations. ✅ Why Map Was Introduced Map was created to solve these exact problems — it’s built specifically for efficient key-value data handling. ✔ Keys can be any type — numbers, objects, functions, arrays, etc. ✔ Maintains insertion order consistently. ✔ Has a built-in .size property. ✔ Offers faster performance for frequent insert/delete operations. ✔ No prototype interference — safer and cleaner. 📌 When to Use What? ✅ Use Object when: - You are representing structured/static data (e.g., user profile, product info, config settings). - Keys are known in advance and mostly strings. - You’re working with JSON-like structures. ✅ Use Map when: - You need a flexible key-value store. - Keys can be numbers, objects, functions, etc. - You frequently add/remove items and need better performance. - You want guaranteed insertion order and a direct .size property. 🛠 Map Quick Reference (Cheat Sheet) Here are the most commonly used Map features in a clean, scannable way 👇 🔹 set(key, value) → Add or update a key-value pair 🔹 get(key) → Retrieve value by key 🔹 has(key) → Check if a key exists 🔹 delete(key) → Remove a specific entry 🔹 clear() → Remove all entries 🔹 size → Returns total number of entries 🔹 map.keys() → Iterator of all keys 🔹 map.values() → Iterator of all values 🔹 map.entries() → Iterator of key-value pairs 🧪 Quick Example: const map = new Map(); map.set("IN", "India"); map.set(1, "One"); map.set({ lang: "JS" }, "JavaScript"); console.log(map.get(1)); // "One" console.log(map.size); // 3 console.log(map.has("IN")); // true 💬 Have you ever used an Object for something that should’ve been a Map? What was the impact? Let’s talk in the comments! #JavaScript #WebDevelopment #Frontend #ProgrammingTips #CodeSmarter #TechLearning
"JavaScript Map vs Object: When to Choose Each"
More Relevant Posts
-
Complete JavaScript Road Map🔥 A-Z JavaScript👇 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS -------------------------- 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest END Hope it helps 😊🌱
To view or add a comment, sign in
-
Complete JavaScript Road Map🔥 A-Z JavaScript👇 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS -------------------------- 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest END
To view or add a comment, sign in
-
👉 JavaScript Deep Dive: Mastering the Singly Linked List Hey Let's dive into a foundational Data Structure that every developer should master: the Singly Linked List (SLL). While arrays are native to JS, understanding and implementing an SLL is crucial for technical interviews and a deeper understanding of how data can be organized efficiently. What is a Singly Linked List? An SLL is a linear data structure where elements are not stored in contiguous memory locations. Instead, it's a collection of individual units called Nodes, where each node: Holds a piece of Data (or value). Contains a Pointer (or reference) to the next node in the sequence. The list is traversed from the Head (the first node) in a single direction until it reaches the end, indicated by a node whose pointer is null. Implementation in JavaScript (The Core) We typically implement an SLL using two classes: Node and SinglyLinkedList. 1. The Node Class This is the building block. JavaScript class Node { constructor(value) { this.value = value; this.next = null; } } 2. The SinglyLinkedList Class This manages the list structure. It usually tracks the head, tail, and length. JavaScript class SinglyLinkedList { constructor() { this.head = null; this.tail = null; this.length = 0; } } Key Operations & Why SLLs Shine The real power of SLLs lies in their performance for certain operations: OperationDescriptionTime ComplexityArray ComparisoninsertAtHeadAdding a node to the beginning of the list.O(1)Arrays require shifting all elements (O(n)).insertAtTailAdding a node to the end of the list.O(1)If you track the tail pointer, it's a simple update.deleteAtHeadRemoving the first node.O(1)Arrays require shifting all elements (O(n)).searchFinding a specific node by its value.O(n)Similar to arrays, you must traverse element by element. The takeaway: If your application frequently requires insertion or deletion at the beginning of a large collection (like implementing a simple Stack or Queue), a Singly Linked List offers superior O(1) performance compared to an array's O(n). Practical Application Singly Linked Lists are often used as the underlying structure for: Stacks (LIFO): Adding/Removing from the head is O(1). Queues (FIFO): Adding to the tail and removing from the head is efficient. Implementing an "Undo" feature in an application. Mastering this fundamental structure will give you a significant edge in building robust and scalable applications. What are your favorite data structures to implement in JavaScript? Share your thoughts below!
To view or add a comment, sign in
-
-
Day 69 of #100DaysOfCode Understanding JavaScript Collections: Sets, WeakSets, Maps & WeakMaps Today I explored how JavaScript handles unique data and key-value pairs through its collection objects Set, WeakSet, Map, and WeakMap. Let’s break it down 👇 🌿 Set A Set stores unique values of any type — numbers, strings, or objects. Duplicates are ignored, and each value appears only once. const trees = new Set(['Baobab', 'Jackalberry', 'Mopane Tree']); trees.add('Breadfruit'); console.log(trees.size); // 4 Common methods: add(), delete(), has(), clear(), forEach(), keys(), values() 🌱 WeakSet A WeakSet only stores objects (no primitives). Its references are “weak,” meaning if the object is no longer used anywhere else, it’s automatically garbage-collected — helping free memory. const treeWeakSet = new WeakSet(); treeWeakSet.add({ name: 'Baobab' }); Key difference: WeakSets are not iterable and don’t expose their contents. FeatureSetWeakSet Type of ValuesAny data typeOnly objects ReferencingStrongWeak IterationIterableNot iterable Use CaseUnique data trackingEfficient memory management 🗺️ Map A Map stores key-value pairs like an object — but with extra powers. Unlike plain objects, keys can be of any type, including objects, arrays, and functions. const myTreesMap = new Map(); myTreesMap.set({ type: 'deciduous' }, 'Maple tree'); myTreesMap.set(42, 'Oak tree'); myTreesMap.set(true, 'Birch tree'); Common methods: set(), get(), has(), delete(), clear(), forEach() ✅ Maps are iterable and have a .size property. 🍃 WeakMap A WeakMap is similar to a Map — but its keys must be objects. It holds weak references, meaning once an object key is no longer used elsewhere, it gets garbage-collected automatically. const myTreeWeakMap = new WeakMap(); myTreeWeakMap.set({ id: 1 }, 'Maple tree'); WeakMap methods: set(), get(), has(), delete() FeatureMapWeakMap Key TypeAny data typeOnly objects Use CaseAssociate data with any keyTrack object-related data IterationIterableNot iterable Size PropertyHas .sizeNo .size 💡 TL;DR: Set → Unique values WeakSet → Unique objects (memory-safe) Map → Key-value pairs of any type WeakMap → Object keys only (memory-safe) 🧩 Each structure has a unique use case. Choose based on what you need: data uniqueness, key-value pairing, or efficient memory management.
To view or add a comment, sign in
-
💡 JSX vs. HTML: Why This "Looks Like" Isn't "Is": The Full-Stack component of building Complex AI Systems often requires a powerful frontend, and for millions of developers, that means React and JSX. A common pitfall for newcomers is confusing JSX with HTML. They look nearly identical, but the difference is profound—and understanding it is key to writing robust, dynamic applications. 1. The Core Identity: What Are They? It's helpful to see the fundamental difference in their roles: HTML (HyperText Markup Language): Purpose: A markup language for structuring static web content. Execution: Natively understood by all web browsers. Role: Defines the structure and content of the page. JSX (JavaScript XML): Purpose: A syntax extension for JavaScript (dynamic logic). Execution: Requires transpilation (e.g., by Babel) into pure JavaScript function calls. Role: Defines what the UI should look like based on component state/logic. 2. The Key Logical Differences The distinction boils down to JavaScript integration: Dynamic Content: In HTML, you need separate <script> tags. In JSX, you embed JavaScript expressions directly inside the markup using curly braces {}. Reserved Keywords: Since JSX is ultimately JavaScript, it must avoid conflict with JS reserved words. For example, JSX uses className instead of the HTML attribute class. 3. The Mechanism: JSX is Just JavaScript Objects! (The "Why") This is the key concept that separates JSX from static HTML: When your code runs, a tool like Babel transpiles the human-readable JSX syntax into pure JavaScript function calls, specifically React.createElement(). The Result: The JSX you write is transformed into a simple JavaScript object (a React Element) that describes what should be rendered on the screen. The browser never sees JSX; it only sees the JavaScript that React uses to efficiently manage the DOM. This allows React to create fast, scalable, and dynamic user interfaces. 🌉 The Full-Stack Bridge: AI, Gen AI, and React As I continue my studies in the IIT Kharagpur AI4ICPS program, I will be posting about both the technical AI/ML concepts and the React/Full-Stack skills needed to deploy these models. Understanding how tools like JSX enable dynamic frontends is crucial, as this is the final layer that delivers the power of Gen AI and Complex AI Systems directly to the user. Challenge: What is one specific instance where treating a JSX attribute like a traditional HTML attribute caused an error in your code (e.g., using class instead of className)? #React #FullStack #GenAI #APIDesign #Programming #WebDevelopment #ArtificialIntelligence #JSX
To view or add a comment, sign in
-
💡 JavaScript Series | Topic 6 | Part 3 — Destructuring: Elegant Data Extraction 👇 Destructuring brought a more elegant, readable, and concise way to extract values from arrays and objects. It’s one of those features that once you start using — you’ll never want to go back. This concept is now fundamental in modern JavaScript, especially in React, Node.js, and API-driven applications. 🧩 Object Destructuring Instead of accessing properties through repetitive dot notation, destructuring lets you unpack exactly what you need — in one clean statement 👇 const user = { name: 'John', age: 30, address: { street: '123 Main St', city: 'Boston' } }; // Basic destructuring const { name, age } = user; // name = 'John', age = 30 // Nested destructuring const { address: { city } } = user; // city = 'Boston' // Renaming variables const { name: userName } = user; // userName = 'John' // Default values const { country = 'USA' } = user; // country = 'USA' (default used because country doesn’t exist) // Rest operator in destructuring const { name: firstName, ...rest } = user; /* firstName = 'John' rest = { age: 30, address: { street: '123 Main St', city: 'Boston' } } */ ⚙️ Why It Matters ✅ Cleaner syntax — eliminates repetitive code ✅ Fewer typos — no long property chains ✅ Safer code — supports defaults for missing values ✅ Easier debugging — extract only what you need 🧠 Real-World Use Cases 1️⃣ API Responses const response = await fetchUserData(); const { name, email, profile: { avatarUrl } } = response; 👉 Perfect for pulling nested API data directly. 2️⃣ React Props function UserCard({ name, age, city }) { return <div>{`${name} (${age}) - ${city}`}</div>; } 👉 Cleaner than writing props.name, props.age, etc. 3️⃣ Config or Env Objects const { PORT, NODE_ENV = 'development' } = process.env; 👉 Great for providing safe defaults in backend code. 💬 My Take: Destructuring makes your code simpler, faster, and safer. It’s not just syntax sugar — it’s a mindset for writing clear, maintainable, and declarative JavaScript. 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions, hands-on coding examples, and performance-driven frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #ES6 #Destructuring #WebDevelopment #ReactJS #NodeJS #NextJS #Coding #TypeScript #ModernJavaScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
#4 Just wrapped up an intense session on the backbone of JavaScript: Arrays and Objects. These aren't just data structures; they're the building blocks for everything we do. Here’s a quick rundown of my key takeaways: JavaScript Deep Dive: Taming Arrays & Objects! 🚀 📌 Arrays: The Ordered Lists More than just [1, 2, 3], arrays are powerhouses with methods that can make or break your code. The Mutable vs. Immutable Showdown: slice(): The polite one. It takes a copy of a section without disturbing the original. splice(): The disruptive one. It removes/replaces elements in the original array. (A classic interview question! ✅) Combining Arrays: Forget push(array) which creates nested arrays! Use concat() or the more modern Spread Operator ... to cleanly merge arrays. Powerful Prototypes: Methods like Array.from() to create arrays from array-like objects (like a string) and flat() to flatten nested arrays are game-changers. 📌 Objects: The Key-Value Kings Objects store structured data, and mastering them is non-negotiable. Two Ways to Create: Object Literals: const obj = { key: 'value' } (Most common) Constructor: Object.create() (Creates a singleton) Constructor method with new Object() Accessing Properties: You can use dot notation (obj.key) or bracket notation (obj["key"]). Bracket notation is essential for keys with spaces or dynamically generated keys. Symbol as a Key: You can use a Symbol for a unique, non-enumerable property key. A hidden gem for defining special properties. Object.freeze() vs. Object.seal(): - freeze(): Makes an object immutable. No changes, additions, or deletions. - seal(): Allows modification of existing properties, but prevents adding or removing new ones. 🔥 Leveling Up: Higher-Order Functions & Destructuring Array Methods that Shine: - map(): Transform each element. (Create a new array of doubled values). - filter(): Select elements based on a condition. - reduce(): Boil down the array to a single value (like a sum). - forEach(): Execute a function for each element (but doesn't return a new array like map). Destructuring Magic: This is a syntax superpower! - Arrays: const [first, second] = myArray - Objects: const { name, email } = userObject It makes code incredibly clean and readable, especially in function parameters and React props. 💡 The Big Revelation: Understanding the difference between shallow copy and deep copy is crucial when working with these structures to avoid unintended side effects. It's amazing how much power is packed into these fundamentals. The more you learn, the more you realize how elegant and powerful JavaScript can be. What's your favorite JavaScript array or object method? Any "aha!" moments when you first understood destructuring? Share below! 👇 #JavaScript #Programming #WebDevelopment #Coding #LearnToCode #SoftwareEngineering #Arrays #Objects #Destructuring #LinkedInLearning #Tech
To view or add a comment, sign in
-
Day 77 of 100DaysOfCode – Understanding Async/Await, JS Engine & Geolocation API 🌍 Let’s break down three key JavaScript concepts every developer should understand 👇 🔹 1. What Is Async/Await, and How Does It Work? JavaScript is asynchronous — meaning it doesn’t wait for long tasks like fetching data or file reading to finish before moving on. That’s where async/await shines. It makes async code look simple and readable, like synchronous code. async function delayedGreeting(name) { console.log("A Messenger entered the chat..."); await new Promise(resolve => setTimeout(resolve, 2000)); console.log(`Hello, ${name}!`); } delayedGreeting("Alice"); console.log("First Printed Message!"); Here, the function pauses for 2 seconds before greeting Alice — but the rest of the program keeps running! We can also handle errors neatly using try/catch: async function fetchUserData() { try { let response = await fetch(`https://lnkd.in/dWvHabH4); let userData = await response.json(); console.log(userData); } catch (error) { console.log("Error fetching user data:", error); } } Async/await = cleaner syntax + better error handling ✨ 🔹 2. How Does the JavaScript Engine Work (and What Is a Runtime)? Think of the JavaScript engine as the “brain” that reads, understands, and executes your code. For example, Google Chrome and Node.js use the V8 Engine. When you run: const greeting = "Hello, World!"; console.log(greeting); The engine: Parses the code (checks for errors) Compiles it into machine-readable bytecode Executes it to print “Hello, World!” But the JavaScript runtime is more than just the engine — it’s the whole environment your code runs in. In the browser → runtime includes the DOM, Fetch API, and timers. In Node.js → runtime includes file systems, HTTP, etc. So the engine executes, while the runtime provides tools to interact with the outside world 🌍 🔹 3. What Is the Geolocation API and How Does getCurrentPosition Work? The Geolocation API lets websites request your location — but only with your permission (for privacy reasons). Example: navigator.geolocation.getCurrentPosition( (position) => { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); }, (error) => { console.log("Error: " + error.message); } ); This uses your device’s GPS, Wi-Fi, or IP address to determine your location. You get a position object that contains details like: latitude longitude accuracy altitude, and more. Always explain why your app needs location data and how it’ll be used — user trust is key. 💡 Wrap-Up: Async/Await simplifies asynchronous programming. JavaScript Engine executes code; Runtime gives it superpowers. Geolocation API helps apps know “where” the user is — responsibly.
To view or add a comment, sign in
-
#9: From Loop Newbie to Array Method Pro in JavaScript! 🚀 Today’s journey took me from basic loops to mastering powerful array methods. If you’ve ever wondered when to use for…of, for…in, forEach, map, filter, or reduce — this post is for YOU 👇 🔁 1. for…of – Best for Iterating Over Iterables (Array / Map) ✅ Returns full value ✅ Can use destructuring in Maps for (const [key, value] of myMap) { console.log(key, value); } ❌ Doesn’t work on plain objects (not iterable). 📍 2. for…in – Works on Objects & Arrays (Keys Only) ✅ Best for objects: for (const key in myObject) { console.log(key, myObject[key]); } ⚠ On arrays, it gives indexes, not values. ❌ Doesn’t work on Map. 📦 3. forEach() – Simple, Clean, No Return ✅ Great for looping arrays ✅ Accepts callback (value, index, array) ✅ Can pass an external function coding.forEach((item, index, arr) => console.log(item, index)); ❌ Doesn’t return anything (undefined always). 🗺️ 4. map() – Returns a New Array ✅ 🔹 Used when you want to transform data. const newArr = nums.map(num => num * 2); ✅ map() → RETURNS ❌ forEach() → DOES NOT RETURN 🧽 5. filter() – Keeps Only What Matches ✅ 🔍 Creates an array based on a condition. const filtered = nums.filter(num => num > 4); ✅ Returns only items that meet criteria. ⛓️ 6. Method Chaining = Cleaner Power Moves ⚡ const result = nums .map(num => num * 10) .map(num => num + 1) .filter(num => num > 50); 📉 7. reduce() – Converts Everything to a Single Value Used for totals, sums, or combining data. const total = prices.reduce((acc, curr) => acc + curr, 0); ✅ Perfect for shopping cart totals, analytics, etc. 🎯 Where You Stand Now: Level → Concept 🟢 Beginner → for...in, for...of 🟡 Intermediate → forEach, map, filter 🔴 Pro → reduce, chaining, destructuring in loops ✨My Takeaway: Once you understand array methods like map, filter, and reduce, you write less code, cleaner logic, and think more like a JavaScript pro. 💡 🧠 Which one confused you the most when you started learning loops in JS? Comment below — let’s grow together! 👇🔥 #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐎𝐛𝐣𝐞𝐜𝐭𝐬 — 𝐀 𝐐𝐮𝐢𝐜𝐤 𝐃𝐞𝐞𝐩 𝐃𝐢𝐯𝐞 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
- 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