Three dots that changed JavaScript: ... The spread operator in action: Arrays: // Copy const copy = [...original] // Merge const all = [...arr1, ...arr2] // Add items const updated = [...items, newItem] Objects: // Copy const clone = { ...user } // Merge const combined = { ...defaults, ...config } // Update const modified = { ...user, age: 30 } Function calls: Math.max(...numbers) fetch(url, { ...defaultOptions, ...customOptions }) Before spread operator: const copy = original.slice() const merged = Object.assign({}, obj1, obj2) fn.apply(null, args) After spread operator: const copy = [...original] const merged = { ...obj1, ...obj2 } fn(...args) The magic: → No mutation (safer code) → Cleaner syntax → Works with any iterable → Essential for React state → Makes immutability easy Three dots. Infinite possibilities.
JavaScript Spread Operator Explained
More Relevant Posts
-
𝗟𝗼𝗼𝗽𝗶𝗻𝗴 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You use loops to repeat a block of code. There are several types of loops in JavaScript: - for loop - while loop - do...while loop - for...of loop - for...in loop Let's look at each type: 1. for loop: You use this loop when you know how many times to repeat the code. for (let i = 1; i <= 5; i++) { console.log("Hello " + i); } 2. while loop: You use this loop when you do not know how many times to repeat the code. let i = 1; while (i <= 5) { console.log(i); i++; } 3. do...while loop: You use this loop when the code must run at least once. let i = 1; do { console.log(i); i++; } while (i <= 5); 4. for...of loop: You use this loop to iterate over arrays. let fruits = ["apple", "banana", "mango"]; for (let fruit of fruits) { console.log(fruit); } 5. for...in loop: You use this loop to iterate over objects. let person = { name: "Anees", age:
To view or add a comment, sign in
-
JS Object vs. Map: Why simple {} might be slow In JavaScript, we often default to using simple objects {} as dictionaries. Most of the time, it works just fine. But there’s a tipping point where choice of data structure directly impacts both performance and code maintainability. I recently refactored a module in one of Node.js services and here is why we should choose Map for heavy-duty tasks: Non-String Keys: In an Object, keys are limited to Strings or Symbols. In a Map, a key can be anything - an object, an array, or even a function. This is a game-changer for metadata caching. Performance: Map is specifically optimized for frequent additions and removals. If your service handles high-frequency data updates, the performance gap becomes noticeable. Predictable Iteration: Unlike Objects, Map always preserves the insertion order of elements. Built-in Size: No more Object.keys(obj).length. You get the size instantly with .size. The bottleneck: We needed to maintain an in-memory cache for user sessions where the key was a complex device configuration object. Initially, we used JSON.stringify(config) to create string keys. The result was massive CPU overhead on serialization and slower lookups as the cache grew. The solution: By switching to a Map, we used the configuration object itself as the key. No serialization, O(1) lookup time, and much cleaner code. #javascript #nodejs #backend #performance #cleancode #Map #datastructures
To view or add a comment, sign in
-
-
Most developers think encapsulation in JavaScript is just about “hiding variables.” It’s more than that. Encapsulation is about controlling access and protecting your logic. 💡 In simple terms: 👉 Keep data safe 👉 Expose only what’s necessary 🔹 1. Using Closures (Classic Way) function createCounter() { let count = 0; return { increment() { count++; console.log(count); }, getCount() { return count; } }; } const counter = createCounter(); counter.increment(); // 1 counter.increment(); // 2 console.log(counter.count); // ❌ undefined ✔ count is private ✔ Accessible only through methods 🔹 2. Using Classes + Private Fields (Modern JS) class BankAccount { #balance = 0; deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const acc = new BankAccount(); acc.deposit(1000); console.log(acc.getBalance()); // 1000 console.log(acc.#balance); // ❌ Error ✔ True private fields ✔ Cleaner and structured ⚡ Why encapsulation matters: • Prevents accidental data changes • Makes code more secure • Improves maintainability • Creates clear boundaries in your system 🧠 The real shift: Don’t just write code that works. Write code that protects itself. What’s your go-to pattern for encapsulation in JavaScript—closures or private fields? 👇 #JavaScript #WebDevelopment #Programming #Frontend #Coding #SoftwareEngineering
To view or add a comment, sign in
-
We think that if a function has ended its execution then we can no longer find the values that was used inside of it. And this is why when we learn JavaScript closures we feel a lot confused. But the thing is, this behaviour only true for values that are stored in stack segment. When you store any value inside a heap segment then you can still access that value via memory address even if the function scope no longer lives In this video we can observe that when we tried to access a scope variable address of one function from another function we could not get the value back, rather got some garbage value But when we stored the value in an address allocated from heap segment then we could get the value back by accessing the address from an entirely different function scope. We could get the value back because the value was never in the stack segment, rather it was in the heap segment But why? why even if we have the memory address, we can not access the value which was assigned into a stack segment memory? Well that is because your compiler adds the instruction of cleaning the stack segment after the function execution. But if we remove that part then yeah you can still get the value back which was stored in the stack segment memory by the previous function Yeah just gives a segmentation fault error :3 but its fine, we got what we were looking for But anyways, the action of storing data into heap segment is the core idea behind the scene of JavaScript closures
To view or add a comment, sign in
-
🚀 map() vs. forEach(): Do you know the difference? The Hook: One of the first things we learn in JavaScript is how to loop through arrays. But using the wrong method can lead to "hidden" bugs that are a nightmare to fix. 🛑 🔍 The Simple Difference: ✅ .map() is for Creating. Use it when you want to take an array and turn it into a new one (like doubling prices or changing names). It doesn't touch the original data. ✅ .forEach() is for Doing. Use it when you want to "do something" for each item, like printing a message in the console or saving data to a database. It doesn't give you anything back. 💡 Why should you care? 1. Clean Code: .map() is shorter and easier to read. 2. React Friendly: Modern frameworks love .map() because it creates new data instead of changing the old data (this is called Immutability). 3. Avoid Bugs: When you use .forEach() to build a new list, you have to create an empty array first and "push" items into it. It’s extra work and easy to mess up! ⚡ THE CHALLENGE (Test your knowledge! 🧠) Look at the image below. Most developers get this wrong because they forget how JavaScript handles "missing" returns. What do you think is the output? A) [4, 6] B) [undefined, 4, 6] C) [1, 4, 6] D) Error Write your answer in the comments! I’ll be replying to see who got it right. 👇 #JavaScript #JS #softwareEngineer #CodingTips #LearnToCode #Javascriptcommunity #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
-
I learned all of this in JavaScript in less than 7 days. And I'm just getting started. Here's everything I covered, from absolute zero: 📦 Variables & Scope → var / let / const → Global, Function & Block Scope → Hoisting + Temporal Dead Zone (TDZ) 🧱 Data Types → Primitives vs Reference Types → Symbols, Ternary Operator ⚙️ Functions → Default Params, Rest & Spread → First-Class & Higher-Order Functions → Pure vs Impure Functions → Arrow Functions → Closures ← this one broke my brain first 📋 Arrays & Methods → sort(), forEach(), map(), filter() → find(), some(), every() 🗂️ Objects → Object basics, properties & methods → Destructuring ✨ ES6+ Syntax → Spread Operator → Array & Object Destructuring I learned all of this. Not because I'm talented. Because I showed up every single day. The study log is in the image, every topic tracked, every concept checked off. If you're also learning JavaScript right now, save this. We're on the same road. 👇 #JavaScript #buildinpublic
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
-
𝗧𝗵𝗲 𝗨𝗹𝗧𝗶𝗺𝗮𝗧𝗲 𝗚𝗨𝗶𝗱𝗲 𝗧𝗼 𝗔𝗿𝗿𝗮𝗬 𝗙𝗟𝗔𝗧𝗧𝗘𝗡𝗜𝗡𝗚 You work with arrays in JavaScript, but they can get nested and hard to use. That's where array flattening comes in. A nested array is an array inside another array. For example: - `[3, 4]` is a nested array - `[5, [6, 7]]` is a deeply nested array Flattening converts a nested array into a single-level array. You can use array flattening in: - API responses with nested data - Data processing and transformation - Simplifying loops and operations - Preparing data for UI rendering There are different ways to flatten arrays: - Using `flat()` - the easiest way in modern JavaScript - Using recursion - important for interviews - Using a stack - an iterative approach When solving flatten problems, think: - Is recursion needed? - Can I reduce complexity? - What is the depth? - Should I preserve order? Array flattening is a must-know concept in JavaScript. It strengthens recursion skills, improves problem-solving ability, and appears frequently in interviews. Source: https://lnkd.in/grRq_v3K
To view or add a comment, sign in
-
One small pattern I really like in JavaScript/TypeScript: return data.items .slice(offset, offset + limit) .map(({ id, firstName, lastName, companyId }) => ({ id, firstName, lastName, companyId, })); Why this is clean: • slice(offset, offset + limit) → handles pagination in a single, readable step • map(...) → transforms data immediately, returning only what’s needed • Object destructuring → avoids repetitive item.id, item.firstName, etc. • No mutations → everything is predictable and functional It’s concise, readable, and does exactly what it needs — nothing more. Sometimes clean code is just about using the right built-in methods. #JavaScript #TypeScript #CleanCode #javascript #remote
To view or add a comment, sign in
-
🧩𝗦𝗶𝗺𝗽𝗹𝗶𝗳𝘆𝗶𝗻𝗴 𝗡𝗲𝘀𝘁𝗲𝗱 𝗗𝗮𝘁𝗮 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Working with deeply nested arrays is a common challenge in JavaScript- especially when data structures start getting complex. To address this, I explored array flattening in depth and documented my learnings: “𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗔𝗿𝗿𝗮𝘆 𝗙𝗹𝗮𝘁𝘁𝗲𝗻𝗶𝗻𝗴 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁” https://lnkd.in/gdzX7d5Z 🔍 What’s covered in the blog: 🔹 How the .flat() method works in JavaScript 🔹 Handling different levels of nesting effectively 🔹 Writing a custom polyfill to understand the underlying mechanics Hitesh Choudhary Piyush Garg Anirudh J. Chai Aur Code Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #Chaicode #Cohort #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode
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
It is very useful