🧠 Day 26 — Rest vs Spread Operator in JavaScript (Simplified) Both use ... — but they do very different things 👀 --- 🔍 The Idea 👉 Spread → Expands values 👉 Rest → Collects values --- ⚡ 1. Spread Operator ... 👉 Expands elements const arr = [1, 2, 3]; const newArr = [...arr, 4]; console.log(newArr); // [1, 2, 3, 4] 👉 Also used in objects const user = { name: "John" }; const newUser = { ...user, age: 25 }; --- ⚡ 2. Rest Operator ... 👉 Collects remaining values function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 --- 🧠 Key Difference Spread → Expands data Rest → Gathers data --- ⚠️ Important Rule 👉 Rest must be last parameter function test(a, ...rest) {} // ✅ --- 🚀 Why it matters ✔ Cleaner code ✔ Flexible functions ✔ Used heavily in React & modern JS --- 💡 One-line takeaway: 👉 “Spread expands, Rest collects.” --- Once you understand this, working with arrays & functions becomes much easier. #JavaScript #ES6 #SpreadOperator #RestOperator #WebDevelopment #Frontend #100DaysOfCode 🚀
Harish Kumar’s Post
More Relevant Posts
-
Why is my code running "out of order"? (Eager vs. Lazy Evaluation) Ever passed a function as an argument and wondered why it executed before the function it was passed into? Look at this common "gotcha": javascript const main = (fn) => { console.log("start"); fn(); console.log("end"); }; const createLogger = (msg) => { console.log("start logger"); return () => console.log(msg); }; // ❌ Unexpected Order: "start logger" -> "start" -> "success" -> "end" main(createLogger("success")); Use code with caution. What’s happening? This is Eager Evaluation. In JavaScript, arguments are evaluated immediately before the outer function runs. Because we used parentheses () on createLogger, JS executes it first to find out what value to give to main. It’s like cooking a 5-course meal before your guests even knock on the door! 🥘 The Fix: Lazy Evaluation 💤 If we want main to control the timing, we need to wrap our logic in a "thunk" (a wrapper function). This tells JS: "Don't run this yet; run it only when I call it." javascript // ✅ Correct Order: "start" -> "start logger" -> "success" -> "end" main(() => createLogger("success")()); Use code with caution. Why does this matter in Node.js? Understanding this distinction is huge for: ✅ Middleware: Deciding when a request starts/ends. ✅ Performance: Avoiding expensive calculations unless they are actually needed. ✅ Closures: Controlling scope and execution timing. Stop executing, start referencing! 🚀 #JavaScript #WebDevelopment #NodeJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
🤔 Wait… shouldn’t variables be deleted? How is it possible that a function still remembers a variable…even after the function where it was created has already finished executing? 😳 👉 Sounds impossible, right? 🚀 JavaScript’s one of the most powerful concepts: Closures 🧠 What is a Closure? A closure is created when a function is defined inside another function, and the inner function can access variables from its parent scope — even after the parent function has finished execution. ⚡Shouldn’t variables be deleted? Normally, yes ✅ 👉 Once a function finishes, its local variables are removed from memory (thanks to garbage collection) But closures change the game 👇 👉 If an inner function is still using those variables, JavaScript keeps them alive in memory 🔍 What’s really happening? The inner function “closes over” its parent’s variables 💡 That’s why it’s called a closure Even though the outer function is done… the inner function still has access to its scope 😮 🔐 Why Closures Matter (Real Use Cases) Closures aren’t just theory — they’re used everywhere: 👉 Encapsulation (Private Variables) Keep data hidden from global scope 👉 Debouncing & Throttling Control function execution (very common in React apps) 👉 State management patterns Maintain data across function calls 💡 Real Developer Insight Closures are powerful… but can be tricky 👉They can also hold memory longer than expected 👉 Misuse can lead to memory leaks 🚀 Final Thought: Most developers use closures unknowingly… But great developers understand how and why they work. #JavaScript #FrontendDevelopment #WebDevelopment #Closures #CodingTips #LearnJavaScript #BuildInPublic #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Function Declaration vs Expression) You write this: sayHi(); function sayHi() { console.log("Hello"); } 👉 Works perfectly ✅ Now try this: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Same idea… same function… Why different behavior? This happens because of Hoisting 📌 What’s happening here? 👉 Function Declarations are fully hoisted So internally: function sayHi() { console.log("Hello"); } sayHi(); 👉 That’s why it works even before definition But for Function Expressions: const sayHello = function () {} 👉 This is treated like a variable (const) So internally: const sayHello; // not initialized (TDZ) sayHello(); // ❌ error 📌 Key Difference: ✔ Function Declaration 👉 Hoisted completely (can call before definition) ✔ Function Expression 👉 Not hoisted like function 👉 Behaves like variable 📌 Bonus case 👇 var sayHello = function () { console.log("Hello"); }; sayHello(); 👉 Works (because var is hoisted) BUT: sayHello(); // before assignment 👉 TypeError ❌ (not a function yet) 💡 Takeaway: ✔ Function declarations → fully hoisted ✔ Function expressions → behave like variables ✔ let/const → TDZ error ✔ var → undefined (then TypeError if called) 👉 Same function… different behavior based on how you write it 🔁 Save this before it confuses you again 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Day 16 — Memoization in JavaScript (Boost Performance) Want to make your functions faster without changing logic? 👉 Use Memoization 🚀 --- 🔍 What is Memoization? 👉 Memoization is an optimization technique where we cache results of expensive function calls and reuse them. --- 📌 Without Memoization function slowSquare(n) { console.log("Calculating..."); return n * n; } slowSquare(5); // Calculating... slowSquare(5); // Calculating again ❌ --- ⚡ With Memoization function memoize(fn) { let cache = {}; return function (n) { if (cache[n]) { return cache[n]; } let result = fn(n); cache[n] = result; return result; }; } const fastSquare = memoize((n) => { console.log("Calculating..."); return n * n; }); fastSquare(5); // Calculating... fastSquare(5); // Uses cache ✅ --- 🧠 What’s happening? 👉 First call → calculates result 👉 Next call → returns from cache 👉 No re-computation --- 🚀 Why it matters ✔ Improves performance ✔ Avoids repeated calculations ✔ Useful in heavy computations ✔ Used in React (useMemo) --- 💡 One-line takeaway: 👉 “Don’t recompute — reuse cached results.” --- If your function is slow, memoization can make it fast instantly. #JavaScript #Performance #Memoization #WebDevelopment #Frontend #100DaysOfCode
To view or add a comment, sign in
-
JavaScript isn’t asynchronous… the environment is. After diving deep into asynchronous JavaScript, I realized something that completely changed how I think about writing code: We don’t “wait” for data… we design what happens when it arrives. 💡 Most developers use fetch and Promises daily, but very few truly understand what happens under the hood. Here’s the real mental model: 🔹 JavaScript is single-threaded 🔹 Heavy operations (API calls, timers) are offloaded to Web APIs 🔹 fetch() returns a Promise immediately (not the data!) 🔹 .then() doesn’t execute your function… it registers it for later 🔥 The game changer? There are actually two queues, not one: Microtask Queue (Promises) → HIGH PRIORITY Callback Queue (setTimeout, etc.) And the Event Loop always prioritizes microtasks. 💥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 . 4 . 3 . 2 🧠 Why this matters: Explains unexpected execution order Makes debugging async code 10x easier Helps avoid common interview pitfalls Builds a strong foundation for React & modern frontend ⚡ Key Insight: Promises are not about cleaner syntax… They are about controlling time and execution order in a non-blocking environment. 📌 Once you truly understand: Event Loop Microtask vs Callback Queue Promise lifecycle You stop guessing… and start predicting behavior. #JavaScript #Frontend #WebDevelopment #AsyncJS #Promises #EventLoop #React #Programming
To view or add a comment, sign in
-
-
For years, sorting an array in JavaScript has been a source of subtle bugs. The `.sort()` method, while functional, mutates the original array in place. This often leads developers to create a copy first, usually with the spread operator `[...]`, before sorting. This "copy-then-sort" pattern is verbose and easily forgotten, especially in complex applications where arrays are passed around. If you forget the copy, you inadvertently modify data in other parts of your program, leading to hard-to-trace bugs and unexpected side effects that can really tank your productivity. Enter `Array.toSorted()`. This modern, immutable alternative returns a new sorted array without touching the original. It's cleaner, safer, and exactly what developers have needed for handling data integrity. It prevents accidental data corruption and makes your code much more predictable. Are you still writing it the old way? #javascript #webdevelopment #frontend #cleancode #js
To view or add a comment, sign in
-
-
How I Understood Memory Leak in JavaScript One day I wrote this small code: let user = { name: "Siddharth" }; let map = new Map(); map.set(user, "Developer"); user = null; console.log(map); And I thought: 👉 “I removed the user… so memory should be free now.” But I was wrong. 🧠 What actually happened? Even after: user = null; The object was still in memory. Why? Because Map was still holding a reference to it. 👉 JavaScript says: “As long as something is pointing to this object, I won’t delete it.” That’s called a memory leak. 💡 Human way to understand this Imagine: You throw something in the dustbin 🗑️ But someone secretly keeps a copy of it. So it’s not really gone. That’s exactly what Map does here. ⚠️ The problem If this keeps happening in a real app: • Memory keeps increasing 📈 • App becomes slow 🐢 • Eventually crashes 💥 ✅ The fix (cleanup) let user = { name: "Siddharth" }; let map = new Map(); map.set(user, "Developer"); user = null; // Cleanup map.clear(); console.log(map); // Map(0) {} Now: 👉 No reference → memory gets freed 🚀 The lesson I learned 📌 Memory leaks happen when references are not removed 📌 Map keeps strong references 📌 Always clean up unused data Now whenever I use Map, I ask: 👉 Am I removing things I no longer need? Still learning JavaScript the human way. 🚀 #JavaScript #MemoryLeak #WebDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #DeveloperJourney #Performance
To view or add a comment, sign in
-
-
One of the most underrated JavaScript features: Destructuring. Not because it's complex,but because once you truly get it, your code never looks the same again. Here's the shift it creates: BEFORE: const a = arr[0]; const b = arr[1]; const name = user.name; const age = user.age; AFTER: const [a, b] = arr; const { name, age } = user; Same logic.But destructuring goes deeper than just shorthand: ✦ Skip indexes in arrays using commas ✦ Rename variables on extraction ✦ Set default values for missing properties ✦ Use ...rest to capture everything remaining ✦ Destructure directly inside function parameters These patterns come up daily, in React, in Node.js, in any codebase that handles real data. I just published a full blog post breaking all of this down with visuals, before/after comparisons, and practical examples. Blog-link: https://lnkd.in/giGUXq7C #JavaScript #JS #WebDev #ProgrammingTips #CleanCode #SoftwareDevelopment
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