😂 25 JavaScript Moments That Break Developers Mentally Every developer starts learning JavaScript with hope. After a few months… they start laughing like a villain in a movie. 😅 Here are 25 JavaScript moments that mentally break developers: 1️⃣ "NaN !== NaN" → Even JavaScript doesn't trust itself. 2️⃣ "typeof null === "object"" → The bug that never left since 1995. 3️⃣ "0.1 + 0.2 = 0.30000000000000004" → Mathematics crying in the corner. 4️⃣ "[] + [] = """ → Empty + Empty = Nothing. Deep philosophy. 5️⃣ "[] + {}" → ""[object Object]"" → JavaScript poetry. 6️⃣ ""5" - 3 = 2" but ""5" + 3 = "53"" → Math depends on JavaScript mood. 7️⃣ "true + true = 2" → Boolean suddenly becomes math genius. 8️⃣ "false == 0" → true But "false === 0" → false JavaScript: Choose your own reality. 9️⃣ "setTimeout(fn, 0)" → runs later… not now. Patience developer. 🔟 "this" keyword → depends on where, when, how, and who called it. 11️⃣ Forgetting "await" → Promise chaos begins. 12️⃣ Arrow functions + "this" → confusion level upgraded. 13️⃣ Accidentally creating global variables without "let" or "const". 14️⃣ Callback hell → looks like a staircase to coding hell. 15️⃣ Infinite "console.log()" debugging. 16️⃣ "undefined" vs "null" → same… but not same. 17️⃣ "parseInt("08")" behaving weird in older browsers. 18️⃣ "==" vs "===" → one line bug that ruins everything. 19️⃣ "map()" used when you needed "forEach()". 20️⃣ "this" inside event handlers doing unexpected drama. 21️⃣ React re-render loop because of one tiny mistake. 22️⃣ "document.querySelector()" returning null when you swear the element exists. 23️⃣ Accidentally mutating objects. 24️⃣ "JSON.stringify()" removing "undefined". 25️⃣ Finally fixing the bug… but you have no idea how it got fixed. Developer after solving it: «“The code works… please nobody touch it.” 🫡» And that’s the secret truth of the internet: Half the web runs on JavaScript. The other half runs on developers praying it doesn’t break. 🔥 If you’re a developer and felt this pain… welcome to the club. #JavaScript #CodingHumor #ProgrammerLife #DevHumor #WebDevelopment #SoftwareDeveloper #TechHumor #ProgrammerMemes #DeveloperProblems #CodeLife #FrontendDeveloper #BackendDeveloper #100DaysOfCode #ProgrammingLife #StackOverflow #Debugging #CodeNewbie #SoftwareEngineering #BuildInPublic #DevelopersLife #madurai #chennai #fresher #job #career #mumbai #bangalore #delhi #ai #germans
25 JavaScript Moments That Break Developers
More Relevant Posts
-
DSA + JavaScript Journey Two mind-expanding topics today — one that makes searching blazing fast, and one that explains how JavaScript actually works under the hood! 🔥 ───────────────────────── 📌 DSA: Binary Search (Recursive) ───────────────────────── After weeks of recursion fundamentals, today I applied it to one of the most important searching algorithms — Binary Search! ⚡ Why Binary Search? → Linear Search = O(n) — checks every element → Binary Search = O(log n) — halves the search space every step → Works only on sorted arrays (increasing or decreasing) 🔍 Core Logic → Calculate mid = start + (end - start) / 2 ← overflow-safe! → If arr[mid] == target → found ✅ → If arr[mid] < target → search right half → If arr[mid] > target → search left half → Base case: start > end → not found ❌ 📌 Important tip: Never use (start + end) / 2 — for large arrays, start + end can overflow a 32-bit integer. Always use start + (end - start) / 2! 🔢 Traced full execution on [8, 11, 15, 20, 22] with target = 15: → mid = 15 → found in 2 steps instead of checking all 5! Also solved the GeeksforGeeks variant — return 1 if found, -1 if not, instead of true/false. Small change, same logic ✅ Linear vs Binary Search comparison: → Linear: O(n), works on any array, index++ per call → Binary: O(log n), sorted only, narrows start/end per call ───────────────────────── 📌 JavaScript Revision: Scope & Execution Context ───────────────────────── This is the topic that makes everything else in JS make sense! 🧠 🌍 Execution Context → Global Execution Context (GEC) — created when JS file runs → Function Execution Context (FEC) — created on every function call → Two phases: Memory Creation phase → Code Execution phase → JS engine uses a Call Stack to manage all execution contexts 🔭 Scope → Global scope — accessible everywhere → Function scope — variables declared inside a function stay inside → Block scope — let and const are block-scoped (inside {}) → var is function-scoped — leaks out of blocks, a common bug source! 🔗 Scope Chain → Inner functions can access outer variables — but not vice versa → JS looks up the scope chain until it finds the variable or hits global 💡 Key insight: Understanding execution context explains why hoisting works, why closures exist, and why var behaves differently from let/const — it all connects! ───────────────────────── Thank you,Rohit Negi Sir! ───────────────────────── From recursion to binary search to how JavaScript runs internally — every concept is taught with real depth and clarity. The way complex ideas are broken into simple steps is truly exceptional. Grateful for every lecture! 🙌 The deeper I go, the more everything connects. The grind continues 💪 #DSA #BinarySearch #Recursion #JavaScript #ExecutionContext #Scope #LearnToCode #100DaysOfCode #CodingJourney #WebDevelopment #Programming #DSAWithRohitNegi
To view or add a comment, sign in
-
-
🚨 JavaScript just silently lied to me — and I almost shipped it to production. Look at this innocent-looking piece of code: **************JS****************** const isTasteGroupSynced = existingTasteGroup.every((eTg) => { return eTg in groupWiseTasteProfileList; }); ************************************ Simple, right? Checks if every element in the array exists as a key in the object. Now ask yourself — what happens when existingTasteGroup is an empty array []? Most developers (including me, initially) would say: ❌ "Nothing matched, so it should return false." JavaScript says: ✅ true Yes. TRUE. With zero iterations. Zero checks. Zero validations. This is called Vacuous Truth — a concept borrowed from logic. .every() on an empty array returns true because there is no element that violates the condition. No counterexample = vacuously true. It makes mathematical sense. But in real-world business logic? It can be a silent, sneaky bug. Imagine this is syncing a user's taste profile. An empty group passes the sync check, your app moves forward, and downstream logic breaks in ways that are incredibly hard to trace. 🛡️ The fix is just one extra guard: ********************JS*********************** const isTasteGroupSynced = existingTasteGroup.length > 0 && existingTasteGroup.every((eTg) => eTg in groupWiseTasteProfileList); ********************************************* One line. Saves hours of debugging. 💡 Lessons you can carry from this: → Never assume — always validate edge cases explicitly → Empty arrays are a valid input, not an afterthought → Code review should ask "what if this is empty?" → JavaScript doesn't lie — it just follows rules we forget exist JavaScript isn't scary. It's just honest about logic in ways we're not always ready for. The real danger isn't the language — it's the assumption. Have you been bitten by .every() or .some() on empty arrays before? Drop it in the comments 👇 #JavaScript #WebDevelopment #CodeQuality #CleanCode #Programming #SoftwareEngineering #FrontendDevelopment #BackendDevelopment #NodeJS #React #JSGotchas
To view or add a comment, sign in
-
-
"I asked a 3+ yr JavaScript dev this question... he picked WRONG! 😵💫" The JavaScript NaN Trap That Breaks Interviews and Production Check the question in attached image and drop your answer (A, B, C, or D) in the comments before you keep reading! No cheating. 😜 ________________________________________ 🛑 𝘛𝘩𝘦 𝘚𝘱𝘰𝘪𝘭𝘦𝘳 𝘈𝘭𝘦𝘳𝘵:Why everyone gets this wrong If you guessed D, congratulations! You’ve survived the JavaScript Hunger Games. 🏹 The Science of the "Wait, What?" In JavaScript, NaN (Not-a-Number) is the only value in the entire language that is not equal to itself. ➡️ 𝐍𝐮𝐦𝐛𝐞𝐫("𝐬𝐢𝐯𝐚") evaluates to NaN. ➡️ So the first line is basically asking: Is 𝐍𝐚𝐍 == 𝐍𝐚𝐍? ➡️ JavaScript responds: "𝐍𝐨𝐩𝐞." 🚩 Even NaN === NaN (strict equality) will return false. This quirk is actually part of the IEEE 754 floating-point standard, but it has caused more production bugs than we'd like to admit. ________________________________________ 🛡️ How to Stop the Bleeding: The Cheat Sheet Don't let your code go "D" in production. Here is your safety kit: 🚀 𝐍𝐮𝐦𝐛𝐞𝐫.𝐢𝐬𝐍𝐚𝐍(𝐯𝐚𝐥) ✅ The Gold Standard. It only returns true if the value is actually NaN. 🚀 𝐎𝐛𝐣𝐞𝐜𝐭.𝐢𝐬(𝐯𝐚𝐥, 𝐍𝐚𝐍) 🧐 The modern, sophisticated way. It treats NaN as equal to NaN. Very reliable. 🚀𝐯𝐚𝐥 !== 𝐯𝐚𝐥🥷 The Hacker Trick. Since NaN is the only thing not equal to itself, if this is true, you’ve found a NaN. 🚀 𝐢𝐬𝐍𝐚𝐍(𝐯𝐚𝐥)⚠️ The Trap. This old-school function coerces the value first. isNaN("hello") is true, which might not be what you wanted! Which one is your go-to? Or do you prefer living on the edge with val !== val? Let's argue in the comments. 👇 hashtag#JavaScript hashtag#WebDev hashtag#CodingInterviews hashtag#ProgrammingTips hashtag#SoftwareEngineering
To view or add a comment, sign in
-
-
DSA + JavaScript Journey Two absolute power topics today — one of the most important sorting algorithms in DSA, and the concept that makes every modern web app work! ───────────────────────── 📌 DSA: Merge Sort (Divide & Conquer) ───────────────────────── Finally cracked Merge Sort — and it's one of the most elegant algorithms I've studied so far! 🔀 The Core Idea — Divide, Conquer, Merge → Divide the array into two halves using mid = start + (end - start) / 2 → Recursively sort the left half, then the right half → Merge the two sorted halves back into one sorted array → Base case: start == end (single element = already sorted) ⚙️ The Merge Step (The Real Magic) → Create a temp array of size (end - start + 1) → Use 3 pointers: left, right, index → Compare arr[left] vs arr[right] — copy the smaller into temp → When one side exhausts, copy remaining from the other → Copy temp back to original array 📊 Time & Space Complexity → Time: O(n log n) — log n levels × O(n) work per level = consistent & efficient → Space: O(n) — temp array dominates over O(log n) stack depth → Why O(n log n)? Each level of the recursion tree does O(n) total merge work, and there are log n levels! 💡 Key lessons: → Always use start + (end - start) / 2 — avoids integer overflow! → Pass array by reference (&arr) in C++ — without it, changes don't reflect → Index must reset to 0 before copying temp back — easy bug to miss! → Array is never physically split — recursion uses indices for efficiency ───────────────────────── 📌 JavaScript Revision: Callbacks, Promises, Async/Await & Fetch API ───────────────────────── This is the topic that makes every real-world web app tick! 🌐 📞 Callbacks → A function passed as an argument to another function → Executes after the parent function completes → Problem: Callback hell — deeply nested callbacks = unreadable, unmaintainable code 😵 🤝 Promises → Represents a value that will be available now, later, or never → Three states: Pending → Fulfilled / Rejected → .then() for success, .catch() for errors, .finally() for cleanup → Solves callback hell with cleaner chaining! ⏳ Async / Await → Syntactic sugar over Promises — makes async code look synchronous → async function always returns a Promise → await pauses execution until the Promise resolves → Wrap in try/catch for clean error handling 🌐 Fetch API → Built-in browser API for making HTTP requests → fetch(url) returns a Promise → .json() parses the response body → Combined with async/await = clean, readable API calls The evolution: Callbacks → Promises → Async/Await Each step solved the problems of the previous. Modern JS uses async/await almost everywhere! 🙏 Thank you, Rohit Negi Sir! Merge Sort and Async JavaScript in the same day — both complex topics made crystal clear with step-by-step explanations and real examples. Every lecture is a masterclass in clarity. Truly grateful, Sir! 🙌 #DSA #JavaScript #Callbacks #WebDevelopment #LearnToCode #100DaysOfCode#Programming
To view or add a comment, sign in
-
-
😂 15 JavaScript Function & Loop Moments That Break Developers Mentally Every developer starts writing functions and loops thinking: “Easy. I got this.” JavaScript after 10 minutes: “Welcome to debugging hell.” 😅 1️⃣ The Infinite Loop while(true){ console.log("Why did I do this?"); } Developer: Laptop fan starts sounding like a helicopter. 2️⃣ Forgot to Increase Counter let i = 0; while(i < 5){ console.log(i); } Developer mind voice: “Oh… that explains the infinite loop.” 3️⃣ Off-By-One Error for(let i = 0; i <= arr.length; i++){ console.log(arr[i]); } Output: undefined appears like an unwanted guest. 4️⃣ Function Without Return function add(a,b){ a + b; } console.log(add(2,3)); Output: undefined Developer: “Where did my 5 go?” 5️⃣ Arrow Function Confusion const add = (a,b) => { a + b } Output: undefined Developer forgot return again. 6️⃣ Callback Chaos setTimeout(()=>{ console.log("Hello"); },1000); console.log("World"); Output: World Hello Developer: “Why is time traveling?” 7️⃣ Loop Inside Loop Disaster for(let i=0;i<1000;i++){ for(let j=0;j<1000;j++){ console.log(i,j); } } Computer: “I’m tired boss.” 8️⃣ Accidentally Mutating Array let arr = [1,2,3]; arr.forEach(num=>{ num = num*2; }); console.log(arr); Developer expecting [2,4,6] Reality: [1,2,3] 9️⃣ Using map but Forgetting Return let nums=[1,2,3]; let result = nums.map(n=>{ n*2 }); console.log(result); Output: [undefined, undefined, undefined] Emotional damage. 🔟 Function Calling Itself Forever function hello(){ hello(); } Browser: Maximum call stack exceeded. 1️⃣1️⃣ Scope Confusion for(var i=0;i<3;i++){ setTimeout(()=>{ console.log(i); },1000); } Output: 3 3 3 Developer expected 0 1 2. 1️⃣2️⃣ let Fixes Everything for(let i=0;i<3;i++){ setTimeout(()=>{ console.log(i); },1000); } Output: 0 1 2 Developer: “Magic.” 1️⃣3️⃣ Forgot Break in Switch switch(day){ case "Monday": console.log("Work"); case "Tuesday": console.log("Still Work"); } Tuesday also prints. 1️⃣4️⃣ Return Inside Loop function find(arr){ for(let i=0;i<arr.length;i++){ return arr[i]; } } Loop ends immediately. 1️⃣5️⃣ Recursive Function Confusion function count(n){ if(n===0) return; console.log(n); count(n-1); } Developer: “Why is my brain hurting?” Truth of programming: 💻 Functions build logic. Loops test your sanity. If you survived debugging JavaScript loops… Congratulations. You are now mentally stronger than most developers. 😅 #JavaScript #CodingHumor #DeveloperLife #ProgrammerMemes #WebDevelopment #SoftwareDeveloper #DebuggingLife #TechHumor #CodeLife #FrontendDeveloper #BackendDeveloper #ProgrammingHumor #DevLife #100DaysOfCode #StackOverflow #BuildInPublic #ProgrammerProblems
To view or add a comment, sign in
-
DSA + JavaScript Revision Journey 🚀 Today was a milestone day — DSA problem solving + one of the most exciting topics in JavaScript! 🙌 ──────────────────────── 📌 DSA: Recursion Problems (Continued) ───────────────────────── Practiced more classic recursion problems today: 🔢 Factorial of N — n! = n × (n-1)! ➕ Sum of First N Natural Numbers — Sum(n) = n + Sum(n-1) ⚡ Power of a Number — num^n = num × num^(n-1) 🔳 Sum of Squares — n² + SumOfSquares(n-1) The golden rule of recursion: break it into ONE subproblem, set a base case, and let the function handle the rest. Every problem follows the same pattern once you train your brain to see it! ───────────────────────── 📌 JavaScript Revision: DOM & Events ───────────────────────── This is where JavaScript truly comes alive — making web pages interactive! 🌐 🌳 DOM (Document Object Model) → Understanding the DOM tree structure → Selecting elements — getElementById, querySelector, querySelectorAll → Manipulating content — innerHTML, textContent, style → Creating & removing elements dynamically ⚡ Events → addEventListener — click, keydown, mouseover, submit → Event object — target, type, preventDefault() → Event bubbling & event delegation → Building interactive UI with JS The moment DOM + Events clicked for me: every button click, form submit, and dropdown on every website you've ever used — it's all powered by this! 🤯 ───────────────────────── 🙏 Thank you, Rohit Negi Sir! ───────────────────────── The explanations are always clear, practical, and full of real-world context. Learning recursion and DOM from you has been an incredible experience. Genuinely grateful, Sir! 🙌 JavaScript is getting more fun every single day. The grind continues 🔥 #DSA #JavaScript #DOM #Events #Recursion #WebDevelopment #LearnToCode #100DaysOfCode #CodingJourney #Frontend #Programming
To view or add a comment, sign in
-
-
💻 Day 89 — Mastering JavaScript Strings, Math & Date Methods Today's learning focused on some of the most commonly used features in JavaScript: String methods, Math operations, Date handling, and OTP generation logic. These concepts are essential for real-world applications such as form validation, authentication flows, text processing, and more. 🎯 What I Learned / Practiced 🔹 JavaScript String Methods — Explored powerful built-in string functions: removing extra spaces using trim(), converting text to lower/upper case, finding characters and words (charAt, indexOf, includes), splitting strings into arrays, repeating content, replacing text, and checking if a string ends with a specific character 🔹 Palindrome & Reverse String Logic — Implemented logic to check whether a given word is a palindrome and reverse a string using JS methods 🔹 Vowel or Consonant Checker — Built a simple exercise that takes a single letter, converts it to lowercase, and checks if it belongs to the vowel group 🔹 JavaScript Math Methods — Practiced using built-in mathematical functions like ceil(), floor(), round(), sqrt(), pow(), and random() for generating values; also learned how coercion happens when JS converts strings to numbers 🔹 JavaScript Date Object — Explored how to extract current date, day of the week, month index, hours, minutes, milliseconds, and timestamps; also worked with custom dates to extract structured parts 🔹 OTP Generation in JavaScript — Created two versions of OTP generation: digit-by-digit OTP using Math.random() and Math.floor(), and a clean function that generates a 6-digit OTP using a single formula 💡 Simple Example I wrote a function that generates a random 6-digit OTP by using Math.random() to create a number between 0 and 999999, then using Math.floor() to remove decimals. This concept is widely used in authentication systems like login verification and password reset flows. 🌱 Reflection / Key Takeaways Today's practice helped me sharpen skills in text processing, mathematical operations, working with dates and time, logic building, and generating secure random data. All these abilities play a huge role in building dynamic, interactive, and real-time web applications. Understanding string and math methods will be very useful when building features like search bars, validations, calculators, and authentication systems. 🔗 Links GitHub:https://lnkd.in/g6_4rknj Live Demo (Vercel):https://lnkd.in/gGMKKyEq 🙏 Thank you for the continuous guidance and support Codegnan | Uppugundla Sairam | Saketh Kallepu | Ambica Kiranmayee Bellamkonda #Day89 #FullStackDevelopment #FrontendDevelopment #JavaScript #StringMethods #MathMethods #DateObject #WebDevelopment #LearningJourney
To view or add a comment, sign in
-
🦎 reasons I always pick TypeScript over Javascript since I'm coding with AI agents, even for little demos, even for scripts: - yeah TypeScript has overhead. setup, compile step, types to write. but you're using agents to code, so you don't do any of that. the agent does it. so why do you care? - the agent can fix its own mistakes. it runs `tsc`, sees the error, corrects it. in JavaScript you either describe the error back manually, set up some MCP connection or test runner so the agent gets runtime feedback, or rely on test coverage to close the loop. all of that works, it's just more setup and you still need to actually hit the right code path to surface the bug. TypeScript catches it without running anything. - 4x fewer regressions in TypeScript projects (2-3% vs 8-12%, Builder.io 2026). 94% of LLM compilation errors are type-check failures, so the compiler is catching exactly the category of mistakes agents make most often - agents use fewer tokens on TypeScript codebases, in my experience, and the community seems to agree. the reason is pretty simple: a compiler error is precise ("line 42, wrong type") so the agent goes straight to the fix. a JavaScript runtime error requires re-reading context, guessing what caused it, trying again. more iterations, more tokens per bug - types give the agent a map. change an interface and it knows every call site that broke. in JavaScript it's guessing from variable names - even for one-off scripts I don't bother with JavaScript anymore. the debugging is just better. and I'm never sure a script won't grow, so I'd rather start right. my brain defaults to TypeScript now and I don't regret it.
To view or add a comment, sign in
-
🤯 20 JavaScript Moments That Break Developers Mentally Every developer thinks they understand true and false. Then JavaScript arrives and says: “Truth is relative.” 😅 1️⃣ Empty Array Is Truthy if([]){ console.log("True"); } Developer: “Why is empty still true?” 2️⃣ But Empty String Is Falsy if("")){ console.log("True"); }else{ console.log("False"); } Output → False JavaScript mood swings begin. 3️⃣ Zero Is False if(0){ console.log("Yes"); }else{ console.log("No"); } Output → No Math teachers confused. 4️⃣ String Zero Is True if("0"){ console.log("True"); } Output → True Developer: “Excuse me?” 5️⃣ Double Negation Trick !!"hello" Output → true Developers using !! like secret magic. 6️⃣ Boolean Conversion Boolean("hello") Boolean("") Output: true false Simple… until it isn’t. 7️⃣ Logical OR Returning Value let name = "" || "Guest"; Output → "Guest" Developer: “Oh… it returns values?” 8️⃣ Logical AND Returning Value let result = "Hello" && "World"; Output → "World" JavaScript: I return the last truthy. 9️⃣ AND Stops Early let result = 0 && "Hello"; Output → 0 Developer: “Short-circuit surprise.” 🔟 OR Stops Early let result = "Hi" || "Hello"; Output → "Hi" First truthy wins. 1️⃣1️⃣ Nullish Confusion let value = null ?? "Default"; Output → "Default" But: let value = "" ?? "Default"; Output → "" Brain: loading… 1️⃣2️⃣ Null Equals Undefined null == undefined Output → true But… null === undefined Output → false JavaScript identity crisis. 1️⃣3️⃣ Array Equals False [] == false Output → true Developer reaction: 😶 1️⃣4️⃣ But Strict Comparison [] === false Output → false Strict equality saves sanity. 1️⃣5️⃣ Object Is Truthy if({}){ console.log("True"); } Output → True Even empty objects feel confident. 1️⃣6️⃣ Number Conversion Chaos Number("") Number(" ") Output: 0 0 Whitespace becomes zero. 1️⃣7️⃣ Weird Boolean Math true + true Output → 2 JavaScript turning logic into arithmetic. 1️⃣8️⃣ Falsy Values List false 0 -0 "" null undefined NaN Everything else = truthy. 1️⃣9️⃣ Unexpected Equality "5" == 5 Output → true Because JavaScript says: “Let me convert things.” 2️⃣0️⃣ The Final Developer Rule if(value){ // probably works } But deep inside… Developer whispers: “Please don’t be undefined.” 😭 Reality of JavaScript: 💻 Type coercion teaches humility. 💻 Truthy & falsy values test your sanity. And the final lesson every developer learns: Always use ===. Always. #JavaScript #CodingHumor #TypeCoercion #DeveloperLife #ProgrammerMemes #WebDevelopment #TechHumor #SoftwareDeveloper #ProgrammingHumor #Debugging #CodeLife #FrontendDeveloper #BackendDeveloper #DevHumor #100DaysOfCode #BuildInPublic #Programmer #problem #StackOverflow #madurai #chennai #fresher #job #career #mumbai #bangalore #delhi
To view or add a comment, sign in
-
Spread & Rest Operators in JavaScript. If you're learning JavaScript, these two operators are super important and very useful in real projects. --- Spread Operator ("...") Definition: The spread operator is used to expand elements of an array or object. It “spreads out” values. Common Use Cases: 1. Copying Arrays const arr1 = [1, 2, 3]; const arr2 = [...arr1]; 2. Merging Arrays const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b]; 3. Copying Objects const user = { name: "Ali", age: 20 }; const newUser = { ...user }; 4. Merging Objects const obj1 = { a: 1 }; const obj2 = { b: 2 }; const merged = { ...obj1, ...obj2 }; 5. Updating Object Values const user = { name: "Ali", age: 20 }; const updatedUser = { ...user, age: 21 }; 6. Passing Array as Function Arguments const nums = [1, 2, 3]; console.log(Math.max(...nums)); --- Rest Operator ("...") Definition: The rest operator is used to collect multiple elements into a single array. It “gathers” values. Common Use Cases: 1. Function Parameters (Unlimited Arguments) function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } 2. Collect Remaining Elements in Array Destructuring const [first, ...rest] = [1, 2, 3, 4]; console.log(rest); // [2, 3, 4] 3. Collect Remaining Properties in Objects const { name, ...others } = { name: "Ali", age: 20, city: "Lahore" }; console.log(others); // { age: 20, city: "Lahore" } --- Key Difference - Spread ("...") → Expands values - Rest ("...") → Collects values --- Simple Tip to Remember: - Spread = “Open / Expand” - Rest = “Collect / Gather” --- If you're learning JavaScript, mastering these will make your code cleaner and more powerful #JavaScript #WebDevelopment #Coding #Frontend #MERN #LearnToCode
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