𝗜𝗳 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗖𝗼𝗻𝗳𝘂𝘀𝗲𝘀 𝗬𝗼𝘂, 𝗬𝗼𝘂𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 𝗔𝗿𝗲𝗻’𝘁 𝗦𝘁𝗿𝗼𝗻𝗴 Ask a JavaScript developer one simple question: “What is hoisting?” Most people answer confidently: “JavaScript moves variables and functions to the top.” And that’s exactly how you know… they don’t really understand JavaScript. Because JavaScript never moves your code. The Hoisting Illusion Hoisting isn’t magic. It’s not code rearrangement. It’s not a compiler trick. Hoisting is a side effect of how JavaScript creates memory before execution. That difference matters, a lot. What Actually Happens (The Real Story) Before any JavaScript code runs, the engine does two phases: 1. Memory Creation Phase Allocates memory for variables and functions Function declarations get fully stored Variables declared with var get undefined let and const are placed in the Temporal Dead Zone (TDZ) 2. Execution Phase Code runs line by line Values are assigned Functions are invoked No code moves. Only memory is prepared. Why Fake Confidence Falls Apart People who memorize hoisting say things like: “let is not hoisted” “Functions are hoisted but variables are not” Both are wrong. Everything is hoisted. The difference is how it’s initialized. That’s why this breaks people: console.log(a); // undefined var a = 10; But this crashes: console.log(b); // ReferenceError let b = 10; Same hoisting. Different memory rules. The Interview Trap Hoisting is dangerous because: Beginners memorize rules Intermediates repeat slogans Seniors explain execution context Interviewers know this. That’s why hoisting questions aren’t about syntax — they’re about mental models. If you understand hoisting, you understand: Execution context Scope Closures The event loop (indirectly) Miss hoisting, and everything else is shaky. Production Reality Check Hoisting bugs don’t show up in tutorials. They show up as: undefined values in production Weird behavior after refactors “Works on localhost, breaks in prod” And the dev says: “JavaScript is weird.” No. Your understanding was shallow. The Real Test of JavaScript Skill If someone can clearly explain: Why var behaves differently What TDZ actually is Why function declarations work before definition They don’t just know JavaScript, they understand it. Final Thought Hoisting doesn’t expose beginners. It exposes pretenders. If you want real JavaScript confidence: Stop memorizing rules Start understanding the engine That’s where real senior devs are made. #javascript
JavaScript Hoisting: Understanding the Engine, Not Just Rules
More Relevant Posts
-
Understanding Event Loop Behavior Through Common Mistakes: While revising the JavaScript event loop, I realized that most confusion doesn’t come from understanding what the event loop is, but from incorrect assumptions we tend to make as beginners. These small misunderstandings can easily lead to wrong conclusions when reasoning about asynchronous code and debugging real-world issues. Trap 1: “setTimeout(fn, 0) runs immediately” Reality: setTimeout callbacks go to the callback queue. They run only after: • the call stack is empty • the microtask queue is fully drained Example: setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); Output: promise timeout 0 ms does not mean immediate. Trap 2: “Microtasks run only once per loop” Reality: • The microtask queue is drained completely every time it is checked. • If a microtask schedules another microtask, it also runs in the same cycle. Example: Promise.resolve().then(() => { console.log("A"); Promise.resolve().then(() => console.log("B")); }); Output: A B Microtasks can chain indefinitely. Trap 3: “Callback tasks run back-to-back” Reality: After each callback task, the event loop: • re-checks the microtask queue • drains it fully • only then executes the next callback Example: setTimeout(() => { console.log("task1"); Promise.resolve().then(() => console.log("micro")); }, 0); setTimeout(() => console.log("task2"), 0); Output: task1 micro task2 Microtasks interrupt callback execution. Trap 4: “Promises are handled by Web APIs” Reality: Promises are part of JavaScript itself. Web APIs only trigger promise resolution (like fetch), but: • .then() callbacks go to the microtask queue Promises are part of JS; Web APIs only resolve them. Trap 5: “fetch callbacks are macrotasks” Reality: • fetch resolves a Promise. • Its .then() callback goes to the microtask queue, not the callback queue. Example: fetch(url).then(() => console.log("fetch")); setTimeout(() => console.log("timeout"), 0); Output: fetch timeout Trap 6 (Node.js): “Browser and Node event loops are identical” Reality: • The concept is the same, but the implementation differs. • Node.js has multiple phases (timers, poll, check, etc.), which affects execution order. Understanding these traps helped me reason about async code more confidently instead of relying on assumptions. If you know other event loop misconceptions that confused you early on, I’d be interested to hear them. #LearnInPublic #CodingJourney #WebDevelopment #JavaScript #ReactJS #DeveloperCommunity #TechContent #Programming
To view or add a comment, sign in
-
Most production JavaScript bugs don’t happen because we forgot syntax. They happen because 𝘄𝗲 𝗳𝗼𝗿𝗴𝗼𝘁 𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝗲𝗮𝗹𝗹𝘆 𝗯𝗲𝗵𝗮𝘃𝗲𝘀. These are the exact patterns behind many late-night debugging sessions: 1) 𝗠𝘂𝘁𝗮𝘁𝗶𝗼𝗻 𝘆𝗼𝘂 𝗱𝗶𝗱𝗻’𝘁 𝗲𝘅𝗽𝗲𝗰𝘁 const arr = [3,1,2]; arr.sort(); // mutates original 🐜 Bug: UI or state shows unexpected order somewhere else. Why: sort() changes the original array. ✅ Fix const sorted = [...arr].sort((a, b) => a - b); 2) 𝙎𝙥𝙖𝙧𝙨𝙚 𝙖𝙧𝙧𝙖𝙮 𝙩𝙧𝙖𝙥 let arr = [1,2,3]; delete arr[1]; arr.map((x) => x*2); // skips the hole 🐜 Bug: Loop runs fewer times than array length. Why: delete creates a hole, array methods skip it. ✅ Fix arr.splice(1,1); 3) 𝙊𝙗𝙟𝙚𝙘𝙩𝙨 𝙖𝙨 𝙠𝙚𝙮𝙨 let obj = {}; obj[{}] = "A"; obj[{}] = "B"; console.log(obj); 🐜 Bug: Cache, memoization, or map overwrites values. Why: Object keys become "[object Object]". ✅ Fix const map = new Map(); map.set({}, "A"); 4) 𝙁𝙡𝙤𝙖𝙩𝙞𝙣𝙜 𝙥𝙤𝙞𝙣𝙩 𝙢𝙖𝙩𝙝 𝙞𝙨𝙨𝙪𝙚 0.1 + 0.2 === 0.3 // false 🐜 Bug: Totals, prices, charts slightly off. Why: Floating point precision. ✅ Fix Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON or, may use libraries like decimal.js or, may use integers (cents instead of dollars) 5) 𝙩𝙝𝙞𝙨 𝙡𝙤𝙨𝙩 𝙞𝙣𝙨𝙞𝙙𝙚 𝙘𝙖𝙡𝙡𝙗𝙖𝙘𝙠 const user = { name: "abc", greet() { return function(){ console.log(this.name) } } }; const newUser = user.greet(); newUser(); // undefined 🐜 Bug: Class methods / handlers lose context. ✅ Fix greet() { return () => console.log(this.name); } Because regular functions have their own 'this' depending on the call site. 6) 𝙀𝙫𝙚𝙣𝙩 𝙡𝙤𝙤𝙥 𝙨𝙪𝙧𝙥𝙧𝙞𝙨𝙚 setTimeout(()=>console.log("timeout"),0); Promise.resolve().then(()=>console.log("promise")); 🐜 Bug: Race conditions in API calls, loaders, state updates. Why: Promises (microtasks) run before timeouts. 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: When apps break, it’s not just about React or Node. It’s: • mutation • references • coercion • event loop timing If you truly understand how JavaScript behaves, Debugging becomes reasoning . #JavaScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #Debugging #JSFundamentals #DevCommunity #Programming
To view or add a comment, sign in
-
🚀 Day 13 of JavaScript Daily Series JavaScript Strings — slice, substring, toUpperCase, trim (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ke 4 most useful string methods seekhenge. Yeh daily life coding me 100% use hote hain — chahe forms ho, search bars ho, validation ho ya UI formatting. 📝 What is a String? (Simple English Definition) A string is a sequence of characters used to store text like names, messages, sentences, etc. Example: let name = "Ritesh Singh"; 1️⃣ slice() — Cut & Extract Part of the String 🔹 Definition Returns a portion of string from start index to end index (end not included). 🧠 Hinglish Explanation Socho tum movie clip ka ek scene cut karke nikalna chahte ho → yahi slice karta hai. 📱 Real-Life Example Instagram username crop karna: let username = "aapanrasoi_official"; let shortName = username.slice(0, 10); console.log(shortName); // "aapanraso" 2️⃣ substring() — Extract Part of String (Like slice, but safer) 🔹 Definition Works like slice but doesn’t accept negative indexes. 🧠 Hinglish Explanation Slice ka hi shareef version — negative cheezein nahi leta. 😄 📱 Example let text = "JavaScript"; console.log(text.substring(4, 10)); // "Script" 3️⃣ toUpperCase() — Convert to CAPITAL Letters 🔹 Definition Returns the string in uppercase. 🧠 Hinglish Explanation Whatsapp pe aise lagta hai jaise koi chillaa kar message bhej raha ho. 😆 📱 Example let city = "varanasi"; console.log(city.toUpperCase()); // "VARANASI" 4️⃣ trim() — Remove Extra Spaces 🔹 Definition Removes spaces from start and end. 🧠 Hinglish Explanation Form bharte time users extra space daal dete hain, trim unko clean kar deta hai. 📱 Real-Life Example (Form Input Clean) let email = " ritesh@gmail.com "; console.log(email.trim()); // "ritesh@gmail.com" 🔥 Quick Summary Table MethodKaamReal Useslice()Part nikalnaUsername / Title Shortensubstring()Safe extractionWord pickingtoUpperCase()Text ko caps meLabels / Highlightstrim()Extra space hatanaForm inputs 🧠 Why These 4 Methods Matter? ✔ Clean data ✔ Better UI ✔ Faster string manipulation ✔ Interviews me 100% pooch lete hain
To view or add a comment, sign in
-
🔍 JavaScript Under the Hood: The Questions That Actually Clear Interviews I’ve worked with JavaScript for years, and the interviews I cleared weren’t because I memorized APIs — they worked because I understood how JavaScript really behaves internally. If you’ve written basic functions, used closures, or handled async/await, you’re already on the right path. The next step is depth. Here are 20 high-impact JavaScript questions that frequently show up in top product-based company interviews — and they test understanding, not syntax 👇 Core Engine & Performance 1️⃣ What is Just-In-Time (JIT) compilation and how does it improve performance? → Baseline vs optimizing compilers in engines like V8. 2️⃣ How do hidden classes and inline caching affect execution speed? → Why consistent object shapes matter. 3️⃣ What is the event loop and how do microtasks vs macrotasks run? → Why Promise.then() executes before setTimeout(). Memory & Execution 4️⃣ How do closures work, and how can they cause memory leaks? → Retained scopes in real apps. 5️⃣ What is the Temporal Dead Zone (TDZ)? → Why let behaves differently from var. 6️⃣ How does JavaScript manage memory in stack vs heap? → Allocation and garbage collection basics. 7️⃣ When should you use WeakMap / WeakSet instead of Map / Set? → Preventing memory leaks. Functions, Context & Behavior 8️⃣ How does this behave in arrow vs regular functions? → Common bugs in event handlers. 9️⃣ How would you implement debounce or throttle from scratch? → Where you’ve used it in real projects. Data Structures & Advanced APIs 🔟 What are Typed Arrays and when should you use them? → Performance vs normal arrays. 1️⃣1️⃣ How does prototype chaining work internally? 1️⃣2️⃣ What’s the difference between pass-by-value and pass-by-reference? 1️⃣3️⃣ How does garbage collection decide what to clean up? 1️⃣4️⃣ What causes stale closures in async code? 1️⃣5️⃣ How does async/await translate under the hood? 1️⃣6️⃣ Why can excessive object mutation slow down apps? 1️⃣7️⃣ How does JavaScript handle tail calls (and why they matter)? 1️⃣8️⃣ What happens when the call stack overflows? 1️⃣9️⃣ How does requestAnimationFrame differ from setTimeout? 2️⃣0️⃣ When does optimizing too early hurt performance? 💡 Interview Insight If you can explain how JavaScript works, not just how to use it, you’ll stand out in interviews, code reviews, and real production discussions. 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content. #JavaScript #FrontendInterviews #WebDevelopment #Interviews #JSInternals #SoftwareEngineering #CareerGrowth
To view or add a comment, sign in
-
JavaScript Promises are not just syntax. They are a way to manage TIME in JavaScript. Let’s break it down clearly 👇 🔹 What is a Promise? A Promise is an object that represents the eventual result of an asynchronous operation. That result can be: • successful • failed • or still waiting Think of a Promise as a “future value”. --- 🔹 Promise States (VERY IMPORTANT) A Promise has exactly THREE states: 1️⃣ Pending → Initial state → Neither fulfilled nor rejected 2️⃣ Fulfilled → Operation completed successfully → A value is available 3️⃣ Rejected → Operation failed → An error reason is available A promise can change state ONLY ONCE. --- 🔹 Creating a Promise const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("Data received"); } else { reject("Something went wrong"); } }); --- 🔹 Consuming a Promise promise .then(data => { console.log(data); }) .catch(error => { console.log(error); }); • `.then()` → runs when fulfilled • `.catch()` → runs when rejected --- 🔹 Important Rule (Many Miss This) Promises themselves are NOT async. The callbacks registered by `.then()` and `.catch()` run asynchronously as MICROTASKS. That’s why: Promise.resolve().then(() => console.log("Promise")); setTimeout(() => console.log("Timeout"), 0); Output: Promise Timeout Promises have higher priority than timers. --- 🔹 Promise Chaining Promises can be chained to avoid callback hell. fetch("/api") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); Each `.then()` returns a NEW promise. --- 🔹 Promise Utilities (Common Interview Topic) • Promise.all() → waits for ALL promises → fails if ANY fails • Promise.allSettled() → waits for ALL → never fails • Promise.race() → resolves/rejects with the FIRST result • Promise.any() → resolves with FIRST fulfilled promise --- 🔹 async / await (Promise Syntax Sugar) async function loadData() { try { const data = await fetch("/api"); console.log(data); } catch (err) { console.error(err); } } `await` pauses the function. The rest runs as a microtask. --- 🔹 Common Mistakes ❌ Assuming promises run immediately ❌ Forgetting error handling ❌ Mixing callbacks and promises ❌ Not returning promises in `.then()` --- 🔹 Mental Model (Senior-Level) 1️⃣ Create a promise 2️⃣ Promise settles (fulfilled/rejected) 3️⃣ `.then()` / `.catch()` queued as microtasks 4️⃣ Event Loop decides execution --- 🔹 Why Promises Matter for Frontend Developers • Data fetching • React side effects • Performance optimization • Predictable async logic Frameworks depend heavily on promises. --- Once you truly understand promises, async code becomes predictable. Follow me for more **ultra-clear JavaScript & frontend explanations**🚀 #javascript #frontend #webdevelopment #interview
To view or add a comment, sign in
-
JavaScript’s eval() — the feature everyone avoids, but few truly understand.. There’s a reason eval() has a bad reputation in JavaScript. But instead of just accepting “never use it”, I wanted to understand why. So I explored it—not for production use, but to understand how JavaScript actually thinks at runtime. What eval() really does At its core, eval() takes a string and executes it as JavaScript code in the current execution context. const x = 10; console.log(eval("x + 5")); // 15 This isn’t magic—it’s JavaScript dynamically injecting code into the engine’s execution phase. The real eye-opener: scope awareness What surprised me most is that direct eval has access to local scope: function testEval() { const secret = "hidden"; eval("console.log(secret)"); } testEval(); // "hidden" This single behavior explains both its power and its danger. It operates inside the scope chain, not outside it. Direct vs Indirect eval — a deep JS concept This distinction reveals how execution context is resolved: const x = 10; // Direct eval eval("x + 5"); // 15 // Indirect eval (0, eval)("x + 5"); // ReferenceError Indirect eval runs in the global scope, not the local one. This subtle difference says a lot about how JavaScript binds scope at runtime. Why JavaScript engines hate it. After experimenting, the concerns make total sense: Executes arbitrary code (huge security risk) Breaks JIT optimizations Defeats static analysis and makes debugging painful eval(userInput); // never trust runtime strings This is why linters, compilers, and senior engineers all warn against it. Does it have any valid use? In rare, tightly controlled scenarios—yes. For example, evaluating validated math expressions: function safeMath(expr) { if (!/^[0-9+\-*/() ]+$/.test(expr)) { throw new Error("Unsafe input"); } return eval(expr); } Even then, safer alternatives usually exist. My key takeaway Exploring eval() taught me far more than avoiding it ever could: How JavaScript resolves scope How execution contexts work Why some features exist even if we rarely use them How runtime behavior impacts performance and security Understanding what not to use is part of becoming a stronger engineer. I won’t use eval() in production—but I’m glad I understood it. Curiosity like this is what helps me write safer, more predictable JavaScript. #JavaScript #FrontendEngineering #WebDevelopment #JSInternals #LearningByDoing #SoftwareEngineering
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗹-𝗞𝗻𝗼𝘄𝗻 𝗦𝘆𝗺𝗯𝗼𝗹𝘀 𝗮𝗻𝗱 𝗧𝗵𝗲𝗶𝗿 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has evolved over time. One major update was the introduction of Symbols in ECMAScript 2015. Well-Known Symbols provide a unique way to define behavior and properties in JavaScript. To understand Well-Known Symbols, you need to know what symbols are. Before ECMAScript 5, JavaScript did not have a way to create private object properties. Developers used tricks like prefixes or closures to manage uniqueness. Here are some key Well-Known Symbols: - Symbol.hasInstance: customizes the behavior of the instanceof operator - Symbol.isConcatSpreadable: determines if an object should be flattened when using Array.prototype.concat - Symbol.iterator: defines the default iterator for an object - Symbol.match: specifies a function used for pattern matching with regex - Symbol.replace: customizes the behavior of String.prototype.replace - Symbol.search: customizes the behavior of String.prototype.search - Symbol.split: determines how String.prototype.split performs on an object You can use Symbol.hasInstance to define custom behaviors for the instanceof operator. For example: class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance) && instance.length > 0; } } You can also use Symbol.iterator to define object iteration. For example: class Fibonacci { constructor() { this.current = 0; this.next = 1; } [Symbol.iterator]() { return this; } next() { const current = this.current; [this.current, this.next] = [this.next, this.current + this.next]; return { value: current, done: false }; } } Well-Known Symbols can streamline code and improve architecture. However, they can also affect performance if used excessively. Source: https://lnkd.in/d_8if4qz
To view or add a comment, sign in
-
🔥 Day 4 of my JavaScript Daily Series! Aaj hum dekhenge JavaScript Strings aur kuch basic methods jo daily coding me bahut kaam aate hain. 💡 What is a String? (Easy English) A String is a sequence of characters — letters, words, or sentences. Basically, text ko store karne ke liye use hota hai. 🧠 Hinglish Explanation Strings: Simple text data type. Name → "Ritesh" Message → "Hello World!" Email → "ritesh@gmail.com" 👉 Real-Life Example: Socho aap apne WhatsApp me message type karte ho — ye sab strings hi hai. 📱 Important String Methods (With Examples) 1️⃣ length Count of characters in string. let name = "Ritesh"; console.log(name.length); // 6 Real-life: Aapke username me kitne letters hai check karna. 2️⃣ toUpperCase() / toLowerCase() Uppercase ya lowercase me convert karna. let city = "mirzapur"; console.log(city.toUpperCase()); // MIRZAPUR console.log(city.toLowerCase()); // mirzapur Real-life: Name standard format me likhna. 3️⃣ charAt(index) Index se character nikalna. let name = "Ritesh"; console.log(name.charAt(0)); // R Real-life: First letter of name ko badge pe show karna. 4️⃣ slice(start, end) String ka part nikalna. let message = "Hello World"; console.log(message.slice(0, 5)); // Hello Real-life: Email ka domain nikalna. 5️⃣ includes(substring) Check karna ki string me word present hai ya nahi. let msg = "I love JavaScript"; console.log(msg.includes("Java")); // true Real-life: Search bar me keyword check karna. 🔥 Quick Summary Table MethodExampleReal-Life Meaninglength"Ritesh".length → 6Count letterstoUpperCase()"mirzapur".toUpperCase() → "MIRZAPUR"Standard formatcharAt(0)"Ritesh".charAt(0) → "R"First letter of nameslice(0,5)"Hello World".slice(0,5) → "Hello"Part of textincludes("x")"I love JS".includes("JS") → trueSearch keyword
To view or add a comment, sign in
-
🚀 Day 12 of JavaScript Daily Series Array Methods — map, filter, reduce (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ke teen sabse powerful array methods padhne wale hain: 👉 map() 👉 filter() 👉 reduce() Yeh teeno tumhari coding life 50% easy bana denge — interviews me MUST-ASK topics! 🧩 1️⃣ map() — Transforming Each Item 🔹 Definition (Simple English) map() creates a new array by applying a function to each item of the original array. 🧠 Hinglish Explanation Socho tum 5 logon ka resume review kar rahe ho. Har ek ka resume padkar tum unki rating assign karte ho. Tumne data modify kiya → yahi map karta hai. 📱 Real-Life Example (Instagram usernames) const users = ["ritesh", "aapanrasoi", "codingbro"]; const usernames = users.map(u => "@" + u); console.log(usernames); // ["@ritesh", "@aapanrasoi", "@codingbro"] map = data ko transform karna 🧩 2️⃣ filter() — Select Only What You Need 🔹 Definition (Simple English) filter() creates a new array containing only those elements that pass a given condition. 🧠 Hinglish Explanation Socho tum job applications check kar rahe ho. Sirf un candidates ko shortlist karoge jinke pass relevant skills hain. Yahi filter karta hai. 📱 Real-Life Example (18+ users) const ages = [12, 18, 20, 15, 30]; const adults = ages.filter(age => age >= 18); console.log(adults); // [18, 20, 30] filter = unwanted data ko hatao, useful data rakho 🧩 3️⃣ reduce() — Reduce Entire Array to One Value 🔹 Definition (Simple English) reduce() processes the array elements and returns a single output (sum, average, object, anything). 🧠 Hinglish Explanation Socho tum shopping cart ka total nikal rahe ho. Sab prices ko add karke one final total banana — reduce ka game. 🛒 Real-Life Example (Shopping cart total) const prices = [200, 450, 120, 300]; const total = prices.reduce((sum, price) => sum + price, 0); console.log(total); // 1070 reduce = saare values ko combine karke ek result 🔥 Quick Summary Table (Super Easy) MethodKaamOutputmap()Transform every itemNew arrayfilter()Keep only matching itemsNew arrayreduce()Combine all itemsSingle value 🧠 Why These Methods Are MUST-KNOW? ✔ Data handling easy ✔ Clean code ✔ Faster development ✔ Used in React, APIs, dashboards, everywhere ✔ Interviewers ALWAYS ask!
To view or add a comment, sign in
-
Difference Between Spread and Rest in JavaScript I remember the first time I saw ... in JavaScript. I thought it was a typo. Three dots sitting there like they forgot to finish typing. Then someone said, “That’s either spread or rest.” Either? Same symbol, different meaning? My brain paused. Many developers hit this moment early in their JavaScript journey. The syntax looks identical, but the behaviour feels opposite. It’s one of those small concepts that seems confusing at first, until it clicks. And once it clicks, your confidence grows, you become a better tech professional, and the codes of other developers becomes easier to reason about. Spread (...) is used to expand values. It takes an array, object, or string and spreads its items out into individual elements. Common uses of spread: Function calls Math.max(...[1, 2, 3]) becomes Math.max(1, 2, 3) Copying arrays or objects (shallow copy) const newArray = [...oldArray] Merging arrays or objects const merged = { ...obj1, ...obj2 } Spread is often used to maintain immutability, especially in frameworks like React(allowing developers to update data without directly altering the original (previous) state). Rest (...) is used to collect values. It takes multiple individual values and packs them into a single array or object. Common uses of rest: Function parameters function myFunc(...args) { // args is an array of all arguments } Destructuring const [first, ...rest] = array; In simple terms: - Spread spreads things out - Rest gathers things together Spread and rest are simple tools, but they unlock powerful patterns in modern JavaScript. Understanding them is not just about syntax, it’s about thinking clearly about how data moves in your code. If this explanation helped, give it a like so more developers can see it. Repost it for someone learning JavaScript. And drop your answer in the comments - which one confused you more when you first learned it? Let’s compare experiences.
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
https://topmate.io/mayank_kumar1/1865008