🔑 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.
JavaScript Set Methods and Usage Examples
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
-
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
-
🧠 𝗗𝗼 𝗬𝗼𝘂 𝗥𝗲𝗮𝗹𝗹𝘆 𝗞𝗻𝗼𝘄 𝗪𝗵𝗮𝘁 `new` 𝗗𝗼𝗲𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? ⤵️ The new Keyword in JavaScript: What Actually Happens ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/dyAXzDHD 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ What actually happens internally when you use `new` ⇢ The 4-step process: create → link → run → return ⇢ Constructor functions & how they really work ⇢ Prototype linking & why it matters ⇢ How instances share methods but keep separate data ⇢ Recreating `new` manually (deep understanding) ⇢ What goes wrong when you forget `new` ⇢ Debugging real-world bugs related to constructors ⇢ new vs ES6 classes — what's really different ⇢ Key tradeoffs & hidden pitfalls Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Programming #SystemDesign #Frontend #Hashnode
To view or add a comment, sign in
-
Every JavaScript developer has shipped this bug: async function processStream(response) { const reader = response.body.getReader() while (true) { const { done, value } = await reader.read() if (done) break processChunk(value) // ← throws an error } reader.releaseLock() // ← never reached. Stream locked forever. } The fix? A try...finally block you have to remember to write every single time. ES2026's using keyword makes this class of bug impossible. 🔒 using readerResource = { reader: response.body.getReader(), [Symbol.dispose]() { this.reader.releaseLock() } } // releaseLock() called automatically — even if processChunk throws Add [Symbol.dispose]() to any class, and using guarantees cleanup when scope exits — on return, on break, or on error. For async resources, await using + [Symbol.asyncDispose] handles it: await using redis = new RedisClient(config) // redis.quit() runs automatically when scope exits The proposal also ships: → DisposableStack — manage multiple resources, disposed LIFO → SuppressedError — preserves both errors if cleanup itself throws → Works in for loops — dispose at end of each iteration TypeScript has supported it since 5.2. Chrome 134+, Firefox 134+, Node.js 22+. Babel transpiles it for older targets. I wrote the complete guide for DB connections, transactions, streams, WebSockets, mutexes, perf timers, and DisposableStack patterns. Have you started using this yet? 👇 #JavaScript #ES2026 #WebDev #NodeJS #Programming #100DaysOfBlogging
To view or add a comment, sign in
-
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
To view or add a comment, sign in
-
JavaScript Event Loop (Microtask vs Macrotask) — explanation We often see this code: console.log("start") setTimeout(() => { console.log("timeout") }, 0) Promise.resolve().then(() => { console.log("promise") }) console.log("end") Output: start end promise timeout Why does this happen? Basic: JavaScript is single-threaded That means it runs one thing at a time (Call Stack) But async tasks like setTimeout and Promise go to different queues. There are two types of queues: Microtask Queue (high priority) Promise.then() async/await Macrotask Queue (low priority) setTimeout setInterval DOM events Event Loop rule (very important): First, all synchronous code runs Then, all microtasks run Then, one macrotask runs Then the loop continues Easy way to remember: Sync → Microtask → Macrotask → Repeat Example breakdown: console.log("start") // sync setTimeout(() => { console.log("timeout") // macrotask }, 0) Promise.resolve().then(() => { console.log("promise") // microtask }) console.log("end") // sync Step by step: start → prints end → prints promise → runs next (microtask, higher priority) timeout → runs last (macrotask) Common mistake: Many people think: “setTimeout with 0ms runs immediately” This is wrong It only goes to the queue, it does not run immediately Final takeaway: JavaScript runs synchronous code first Then microtasks (Promise) Then macrotasks (setTimeout) Pro tip: If you understand this concept well, it will help you with: API handling React state updates Debugging async issues
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unlocking the Power of Map and Set Data Structures in JavaScript Ever wondered how to manage collections of data more effectively? Let's dive into Maps and Sets! #javascript #datastructures #map #set ────────────────────────────── Core Concept Have you ever found yourself needing a way to store unique values or key-value pairs? Maps and Sets might just be the perfect solution for you! They offer powerful features that can simplify your data management. Key Rules • A Map stores key-value pairs where keys can be of any type. • A Set stores unique values, ensuring no duplicates. • Both structures maintain the insertion order, which can be very handy! 💡 Try This const myMap = new Map(); myMap.set('name', 'Alice'); myMap.set('age', 30); const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(1); // won't be added again ❓ Quick Quiz Q: What will happen if you try to add a duplicate value to a Set? A: It will be ignored, as Sets only store unique values. 🔑 Key Takeaway Leverage Maps for key-value storage and Sets for unique collections to streamline your JavaScript code!
To view or add a comment, sign in
-
🧸 Closure — Story First Imagine: 👉 A child goes outside to play 👉 But he still remembers what’s inside his house That’s a closure. 👉 A function goes outside its original scope 👉 But still remembers variables from where it was created 🧠 Real Definition:- A closure is a javascript feature where a function remembers and can access variables from its outer (lexical) scope even after the outer function has finished executing. ⚙️ Behind the Scenes (JS Engine) 💡 Example:- function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); counter(); 📦 Step 1: Global Execution Context Created 1- Stored in Call Stack 2- Memory allocated: outer → function counter → undefined ⚙️ Step 2: outer() is called 👉 New Execution Context created for outer :- Inside its memory: count = 0 inner = function() {...} 👉 Normally, when outer() finishes → its memory should be deleted ❌ BUT… 👉 JavaScript sees: “inner function is still using count” So it does something special: 🔥 Closure is Created 👉 JS keeps count alive in memory 👉 Even after outer() is finished This saved memory is called: 👉 Lexical Environment ⚡ Step 3: Execution counter(); → 1 counter(); → 2 👉 Because count is remembered (not destroyed) 🧠 Where is this stored? 👉 The closure data is stored in: Execution Context memory Referenced via Scope Chain Internally kept in Heap (because it persists) (Heap is a region of memory where JavaScript stores reference types like objects, arrays, and functions.) 🔥 Why Closures Matter (Real World) Data privacy (private variables) React hooks Callbacks Event handlers #JavaScript #FrontendDeveloper #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unlocking the Power of Proxy and Reflect in JavaScript Let's dive into the Proxy and Reflect APIs in JavaScript and how they can enhance your coding skills. #javascript #proxy #reflect #webdevelopment ────────────────────────────── Core Concept Have you ever wished you could intercept and customize operations on objects? The Proxy and Reflect APIs might be just what you need! They allow you to define custom behavior for fundamental operations (like property lookup and assignment) on objects. Are you ready to explore how they work? Key Rules • Proxies can intercept operations on objects (e.g., get, set). • Reflect provides methods to operate on objects directly, making it easier to manipulate them. • Both tools enable more dynamic and robust code, reducing boilerplate. 💡 Try This const target = { name: 'Alice' }; const handler = { get: (obj, prop) => Hello, ${obj[prop]}! }; const proxy = new Proxy(target, handler); console.log(proxy.name); // Outputs: Hello, Alice! ❓ Quick Quiz Q: What is the primary purpose of using a Proxy in JavaScript? A: To define custom behavior for fundamental operations on objects. 🔑 Key Takeaway Leverage Proxy and Reflect to write cleaner, more powerful JavaScript code!
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