🚀 Where to Use Spread (...) and Rest (...) Operators in JavaScript (Real Use Cases) Many developers know spread and rest… But the real question is 👉 Where should you actually use them? 🔹 Spread Operator (...) → “Expand Values” 👉 Use spread when you want to open / copy / merge data 1. Copy Arrays (Avoid Bugs) const arr = [1, 2, 3]; const copy = [...arr]; 👉 Without spread: const copy = arr; // ❌ same reference (danger) 2. Merge Arrays const a = [1, 2]; const b = [3, 4]; const result = [...a, ...b]; 👉 Very common in real apps 3. Update Objects (Immutability – VERY IMPORTANT in React) const user = { name: "Javascript" }; const updatedUser = { ...user, age: 21 }; 👉 Don’t mutate original object 4. Pass Array as Function Arguments const nums = [5, 10, 2]; Math.max(...nums); 5. Clone Objects const newUser = { ...user }; 👉 Used in state updates (React) 🔹 Rest Operator (...) → “Collect Values” 1. Functions with Unlimited Arguments function sum(...numbers) { return numbers.reduce((a, b) => a + b); } 👉 Flexible functions 2. Separate Values from Array const [first, ...rest] = [1, 2, 3, 4]; 👉 Extract first → collect remaining 3. Remove Properties from Object const user = { name: "Javascript", age: 21, city: "Hyd" }; const { name, ...others } = user; 👉 Useful for filtering data 4. Handling API Data const { id, ...userData } = response; 👉 Separate important fields >>>Spread = “Break it apart” >>> Rest = “Bring it together” “Both use ... , how do you differentiate?” It depends on context — >> If it’s expanding values → Spread >> If it’s collecting values → Rest Example: function demo(a, b, ...rest) { console.log(a, b, rest); } const arr = [1, 2, 3, 4]; demo(...arr); #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode
JavaScript Spread and Rest Operators: Real Use Cases
More Relevant Posts
-
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
-
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
-
Many developers confuse slice() and splice() in JavaScript. The difference is simple but important. 1️⃣ slice() — Creates a copy slice() returns a portion of an array without changing the original array. Example: const numbers = [10, 20, 30, 40, 50] const result = numbers.slice(1, 4) Result → [20, 30, 40] Original → [10, 20, 30, 40, 50] Use it when you want to extract data safely without modifying the source array. 2️⃣ splice() - Modifies the array splice() changes the original array. It can remove, add, or replace elements. Example 1 - Remove items: const numbers = [10, 20, 30, 40, 50] numbers.splice(2, 2) Result → [10, 20, 50] It removed 30 and 40 from the original array. Example 2 - Add Items : constnumbers= [10, 20, 50]; numbers.splice(2, 0, 30, 40); console.log(numbers); // [10, 20, 30, 40, 50] Explanation: It Start at index 2, Remove 0 items and Insert 30 and 40 Key Difference slice() → non-destructive (does not modify the array) splice() → destructive (modifies the array) Quick rule to remember slice → copy splice → change Understanding this small difference prevents many bugs, especially when working with React state and immutable data patterns. #javascript #webdevelopment #frontend #reactjs #programming
To view or add a comment, sign in
-
{JS Problem Solving} Today, I solved some JavaScript problems to improve my problem-solving skills. Problems I solved=> 1. Deep Flatten Array No matter how deep the nested array is, make it completely flat flatten([1, [2, [3, [4]], 5]]) // output: [1,2,3,4,5] 2️. Debounce function Create a function that will execute with a delay if called rapidly debounce(fn, 500) Real use: search input optimization 3️. Throttle Function Run the function only once in a specified time throttle(fn, 1000) Real use: scroll event 4️. Custom Promise.all() Implement it yourself myPromiseAll([p1, p2, p3]) Output: Return the result if all are resolved 5️. LRU Cache Implement Least Recently Used cache const cache = new LRUCache(2) cache.put(1, 1) cache.get(1) Real use: browser caching 6️. Group By Function Group an array groupBy(users, "age") 7️. Deep Clone Object clone nested object (no reference) deepClone(obj) JSON.parse cannot be used 8️. Infinite Curry Function Will support unlimited chaining sum(1)(2)(3)(4)() // 10 9️. Event Emitter (Node.js style) Create a custom event system emitter.on("click", fn) emitter.emit("click") 10. Retry API Call with Limit API will retry if it fails retry(fetchData, 3) Repo link: https://lnkd.in/gXtcS9qP #problemsolver #programmer #javascriptdeveloper
To view or add a comment, sign in
-
-
🚀 JavaScript Deep Dive: `this` Keyword (Most Confusing Yet Most Asked) If you think `this` always refers to the current object… You’re already making a mistake ❌ Let’s simplify it 👇 --- 💡 Rule: 👉 `this` depends on **HOW a function is called**, not where it is written. --- 💻 Example 1 (Implicit Binding): ```js const user = { name: "Rahul", greet() { console.log(this.name); } }; user.greet(); // Rahul ✅ ``` 👉 Here, `this` → `user` --- 💻 Example 2 (Losing Context): ```js const greetFn = user.greet; greetFn(); // undefined ❌ ``` 👉 `this` is now global (or undefined in strict mode) --- 💻 Example 3 (Arrow Function Trap): ```js const user = { name: "Rahul", greet: () => { console.log(this.name); } }; user.greet(); // undefined ❌ ``` 👉 Arrow functions don’t have their own `this` 👉 They take it from **parent scope** --- 💻 Example 4 (Explicit Binding): ```js function greet() { console.log(this.name); } const user = { name: "Rahul" }; greet.call(user); // Rahul ✅ ``` --- 🔥 4 Golden Rules of `this`: 1. Global → window (or undefined in strict mode) 2. Implicit → object before dot 3. Explicit → call/apply/bind 4. New → new object created --- 💥 Interview Trap: 👉 Question: Why arrow functions are not suitable for object methods? ✅ Answer: Because they don’t have their own `this`, leading to unexpected results. --- 🎯 One Line to Remember: 👉 `this` = “Who is calling me?” --- #javascript #webdevelopment #frontend #reactjs #codinginterview #learnjavascript #developers #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Shallow Copy vs Deep Copy in JavaScript Ever copied an object and accidentally changed the original? That’s not a bug… that’s reference behavior in JavaScript. 🧠 What Happens When You Copy Data? In JavaScript, objects and arrays are stored by reference, not by value. 👉 So when you “copy” them, you might just be copying the address, not the actual data. 🔹 1. Shallow Copy (⚠️ Partial Copy) A shallow copy copies only the top level. Nested objects/arrays still share the same reference. 📌 Example: const student = { name: "Javascript", marks: { math: 90 } }; const copy = { ...student }; copy.marks.math = 50; console.log(student.marks.math); // 50 (original changed!) What just happened? 👉 You changed the copy… 👉 But the original also changed! 💡 Reason: Only the outer object was copied marks is still the same reference ✅ How to Create Shallow Copy // Objects const copy1 = { ...obj }; const copy2 = Object.assign({}, obj); // Arrays const arrCopy = [...arr]; 🔹 2. Deep Copy (✅ Full Independent Copy) A deep copy creates a completely new object, including all nested levels. 👉 No shared references → No accidental changes 📌 Example: const deepCopy = structuredClone(student); deepCopy.marks.math = 50; console.log(student.marks.math); // ✅ 90 (original safe) ✅ Modern Way (Recommended) const deepCopy = structuredClone(user); 👉 Handles nested objects properly ⚡ Key Takeaway 👉 If your object has nested data, shallow copy is NOT enough #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #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
-
JavaScript in 2026: The Dev Update You Didn't Know You Needed ECMAScript continues to evolve, and this year's updates are particularly noteworthy for JavaScript developers. Here’s a comprehensive overview of what’s new, what’s on the horizon, and why it matters. 1. Temporal API — The Biggest JS Feature in Years (ES2026) Date handling in JavaScript has faced challenges since 1995. With the Temporal API, that’s changing. const now = Temporal.Now.zonedDateTimeISO("Asia/Kolkata"); console.log(now.toLocaleString()); // Correct. Always. 2. using keyword — Automatic Resource Cleanup (ES2026) This feature simplifies resource management in asynchronous functions. async function saveData() { await using file = new FileHandle("output.txt"); await file.write("hello"); // file auto-closed here, even on error } No more worries about forgetting to close database connections or file handles. The runtime ensures cleanup when the variable goes out of scope, which is a significant improvement for server-side Node.js development. 3. Iterator Helpers — Lazy Evaluation (ES2025) This update enhances efficiency by allowing lazy evaluation without creating extra arrays. // Old way: creates 3 new arrays array.map(x => x*2).filter(x => x>10).slice(0, 3); // New way: zero extra arrays, stops after 3 Iterator.from(array).map(x => x*2).filter(x => x>10).take(3).toArray(); This feature works seamlessly with Sets, Maps, Generators, and any iterable, improving performance and memory usage. Additional updates include: - Array.fromAsync() — Collect async generator results into an array effortlessly - Iterator.concat() — Lazily iterate across multiple pages/sources - Error.isError() — Reliably detect real Error #JavaScript #ECMAScript2026 #WebDevelopment #TypeScript #FrontendDev #NodeJS #Programming #SoftwareEngineering #TechNews #CodingLife
To view or add a comment, sign in
-
-
Day 5 ⚡ Async/Await in JavaScript — The Clean Way to Handle Async Code If you’ve struggled with .then() chains, async/await is your best friend 🚀 --- 🧠 What is async? 👉 Makes a function always return a Promise async function greet(){ return "Hello"; } greet().then(console.log); // Hello --- ⏳ What is await? 👉 Pauses execution until a Promise resolves function delay(){ return new Promise(res => setTimeout(() => res("Done"), 1000)); } async function run(){ const result = await delay(); console.log(result); } --- ⚡ Why use async/await? ✔ Cleaner than .then() chaining ✔ Looks like synchronous code ✔ Easier error handling --- ❌ Sequential vs ⚡ Parallel // ❌ Sequential (slow) const a = await fetchUser(); const b = await fetchPosts(); // ⚡ Parallel (fast) const [a, b] = await Promise.all([ fetchUser(), fetchPosts() ]); --- ⚠️ Error Handling try { const data = await fetchData(); } catch (err) { console.log("Error handled"); } --- 💡 One-line takeaway 👉 async/await = cleaner + readable way to handle Promises #JavaScript #AsyncAwait #WebDevelopment #Frontend #Coding #100DaysOfCode
To view or add a comment, sign in
-
🧠 Day 25 — JavaScript Destructuring (Advanced Use Cases) Destructuring isn’t just syntax sugar — it can make your code cleaner and more powerful 🚀 --- 🔍 What is Destructuring? 👉 Extract values from arrays/objects into variables --- ⚡ 1. Object Destructuring const user = { name: "John", age: 25 }; const { name, age } = user; --- ⚡ 2. Rename Variables const { name: userName } = user; console.log(userName); // John --- ⚡ 3. Default Values const { city = "Delhi" } = user; --- ⚡ 4. Nested Destructuring const user = { profile: { name: "John" } }; const { profile: { name } } = user; --- ⚡ 5. Array Destructuring const arr = [1, 2, 3]; const [a, b] = arr; --- ⚡ 6. Skip Values const [first, , third] = arr; --- 🚀 Why it matters ✔ Cleaner and shorter code ✔ Easier data extraction ✔ Widely used in React (props, hooks) --- 💡 One-line takeaway: 👉 “Destructuring lets you pull out exactly what you need, cleanly.” --- Master this, and your code readability improves instantly. #JavaScript #Destructuring #WebDevelopment #Frontend #100DaysOfCode 🚀
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