#js #18 **Spread and Rest Operator** Spread (...) and Rest (...) look the same in JavaScript, but they do opposite jobs depending on where you use them. 🔹 1. Spread Operator (...) 👉 Expands (unpacks) elements Used when you want to take values out of an array/object ✅ Examples 📌 Array Spread const arr1 = [1, 2, 3];const arr2 = [...arr1, 4, 5];console.log(arr2); // [1, 2, 3, 4, 5] 📌 Copy Array (Important ⚠️) const original = [1, 2, 3]; const copy = [...original]; copy.push(4); console.log(original); // [1, 2, 3] console.log(copy); // [1, 2, 3, 4] 👉 Avoids reference issues (unlike direct assignment) 📌 Merge Arrays const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b]; 📌 Object Spread const user = { name: "Navnath", age: 28 }; const updated = { ...user, city: "Nagpur" }; 📌 Function Arguments const nums = [1, 2, 3]; function sum(a, b, c) { return a + b + c;} sum(...nums); // 6 🔹 2. Rest Operator (...) 👉 Collects (packs) elements into one Used when you want to gather multiple values into a single variable ✅ Examples 📌 Function Parameters function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);} sum(1, 2, 3, 4); // 10 👉 numbers becomes an array 📌 Array Destructuring const arr = [1, 2, 3, 4]; const [first, ...rest] = arr; console.log(first); // 1 console.log(rest); // [2, 3, 4] 📌 Object Destructuring const user = { name: "Navnath", age: 28, city: "Nagpur"}; const { name, ...others } = user; console.log(name); // Navnath console.log(others); // { age: 28, city: "Nagpur" } key difference: | Feature | Spread (`...`) | Rest (`...`) | | ---------- | ---------------- | --------------- | | Purpose | Expand values | Collect values | | Usage side | Right side (RHS) | Left side (LHS) | | Example | `[...arr]` | `[a, ...rest]` | 🧠 Easy Way to Remember Spread → “Break it” (expand) Rest → “Collect it” (gather) ⚠️ Common Mistake const obj = { a: 1, b: 2 }; const newObj = { ...obj, a: 10 }; 👉 Output: { a: 10, b: 2 } ✔️ Last value overrides previous ones #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
Spread and Rest Operator in JavaScript Explained
More Relevant Posts
-
#js #15 **This Keyword** In JavaScript, the this keyword refers to the context in which a function is executed—basically, “who is calling this function.” But unlike many other languages, this in JavaScript is dynamic (it changes depending on how the function is called, not where it’s written). 🔹 1. Global Context In the global scope: console.log(this); In browsers → window In Node.js → global (or {} in strict modules) 🔹 2. Inside an Object Method When used inside an object: const person = { name: "Alice", greet() { console.log(this.name); } }; person.greet(); // Alice 👉 this refers to the object calling the method (person). 🔹 3. Inside a Regular Function function show() { console.log(this); } show(); Non-strict mode → window Strict mode → undefined 🔹 4. Arrow Functions (Important ⚠️) Arrow functions do NOT have their own this. They inherit it from the surrounding (lexical) scope. const obj = { name: "Bob", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Here, this is NOT obj, it’s from the outer scope. 🔹 5. Event Handlers button.addEventListener("click", function () { console.log(this); // the button }); 👉 this refers to the element that triggered the event 🔹 6. Constructor Functions / Classes function Person(name) { this.name = name; } const p = new Person("John"); console.log(p.name); // John 👉 this refers to the newly created object 🔹 7. Explicit Binding (call, apply, bind) You can manually set this: function greet() { console.log(this.name); } const user = { name: "Emma" }; greet.call(user); // Emma Summary: | Situation | `this` refers to | | ------------------- | --------------------------- | | Global scope | Global object | | Object method | The object | | Regular function | Global / undefined (strict) | | Arrow function | Lexical (outer) `this` | | Constructor (`new`) | New instance | | Event handler | Element triggering event | | `call/apply/bind` | Explicitly set value | #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
POST 1 — The JavaScript Event Loop Is Not What You Think ⚙️ Every JavaScript developer says they understand the event loop. Most of them don't. And that gap is exactly why async bugs are so hard to find and fix. Here's what's actually happening 👇 ───────────────────────── First — JavaScript is single-threaded. Always. One thread. One call stack. One thing running at a time. So how does it handle timers, fetch calls, and user events without freezing? It doesn't. The BROWSER does. And then it reports back. ───────────────────────── The pieces most developers mix up: The Call Stack → where your code actually runs. Functions get pushed in, executed, and popped out. This is the only place code runs. Web APIs → setTimeout, fetch, DOM events. These live OUTSIDE the JS engine — in the browser or Node runtime. They run in separate threads you never manage. The Task Queue (Macrotask Queue) → where callbacks from Web APIs wait to be picked up. setTimeout callbacks land here. The Microtask Queue → where Promise callbacks and queueMicrotask calls wait. This queue has HIGHER priority than the task queue. ───────────────────────── The loop itself: 1. Run everything currently on the call stack until it's empty 2. Drain the ENTIRE microtask queue — every single item, including new ones added during draining 3. Pick ONE task from the task queue 4. Go back to step 1 ───────────────────────── Why this produces bugs nobody expects: Promise.resolve().then() runs before setTimeout(() => {}, 0) — always. Microtasks can starve the task queue if you keep adding new ones during draining. Long synchronous code blocks EVERYTHING — no timers fire, no events respond, no UI updates. ───────────────────────── The practical rule: Never put heavy computation directly on the call stack. Break it up. Use setTimeout to yield back to the event loop. Keep microtask chains short and predictable. ───────────────────────── Did the microtask vs task queue distinction surprise you? Drop a comment below 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #WebPerformance
To view or add a comment, sign in
-
#js #19 **Optional Chaining in Javascript** Optional Chaining (?.) in JavaScript is used to safely access nested properties without causing errors if something is null or undefined. 🔹 Why We Need It Without optional chaining: const user = null; console.log(user.name); // ❌ Error: Cannot read property 'name' 👉 This crashes your code. ✅ With Optional Chaining const user = null; console.log(user?.name); // undefined ✅ (no error) 👉 If user is null or undefined, it stops and returns undefined 🔹 Syntax obj?.propertyobj?.[key]obj?.method() ✅ Examples 📌 1. Nested Objects const user = { profile: { name: "Navnath" }}; console.log(user?.profile?.name); // Navnath console.log(user?.address?.city); // undefined 📌 2. Function Calls const user = { greet() { return "Hello"; }}; console.log(user.greet?.()); // Hello console.log(user.sayHi?.()); // undefined (no error) 📌 3. Arrays const arr = [1, 2, 3]; console.log(arr?.[0]); // 1 console.log(arr?.[5]); // undefined 🔥 Real Use Case (Very Common) const response = { data: { user: { name: "Navnath" } }}; const name = response?.data?.user?.name; 👉 Avoids writing multiple checks like: if (response && response.data && response.data.user) ... ⚠️ Important Points ❌ Doesn’t Work on Undeclared Variables console.log(user?.name); // ❌ if user is not defined at all ⚠️ Stops Only on null / undefined const obj = { value: 0 }; console.log(obj?.value); // 0 ✅ (not skipped) 🔥 Combine with Nullish Coalescing (??) const user = {}; const name = user?.name ?? "Guest"; console.log(name); // Guest 🧠 Easy Memory Trick ?. → "If exists, then access" Otherwise → return undefined, don’t crash #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
#js #16 **Destructuring Arrays** Array destructuring in JavaScript is a way to extract values from an array and assign them to variables in a single line. 🔹 Basic Idea Instead of doing this: const arr = [10, 20, 30]; const a = arr[0]; const b = arr[1]; const c = arr[2]; 👉 You can do: const arr = [10, 20, 30]; const [a, b, c] = arr; ✔ Cleaner ✔ Shorter ✔ More readable 🔹 1. Simple Example const colors = ["red", "green", "blue"]; const [first, second, third] = colors; console.log(first); // red console.log(second); // green 🔹 2. Skip Values const numbers = [1, 2, 3, 4]; const [a, , c] = numbers; console.log(a); // 1 console.log(c); // 3 👉 Notice the empty space (, ,) skips values. 🔹 3. Default Values const arr = [10]; const [a, b = 20] = arr; console.log(a); // 10 console.log(b); // 20 (default) 🔹 4. Swap Variables let x = 1; let y = 2; [x, y] = [y, x]; console.log(x); // 2 console.log(y); // 1 🔹 5. Rest Operator (...) const numbers = [1, 2, 3, 4, 5]; const [first, ...rest] = numbers; console.log(first); // 1 console.log(rest); // [2, 3, 4, 5] 🔹 6. Nested Array Destructuring const arr = [1, [2, 3]]; const [a, [b, c]] = arr; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3 🔹 7. Function Return Example function getUser() { return ["Rahul", 25]; } const [name, age] = getUser(); console.log(name); // Rahul 🔹 8. Real Use Case (React) Very common in React: const [count, setCount] = useState(0); 👉 Here: count = current state setCount = function to update it 🔥 Summary Use [] on the left side Order matters You can skip, set defaults, and use rest Makes code clean and concise #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
#js #8 **Why JavaScript Is Single Threaded Synchronous Language** 🧠 Statement: 👉 “JavaScript is single-threaded and synchronous” We’ll break this into parts so it’s easy to understand. 🧵 1. What is Single-Threaded? 👉 JavaScript has only ONE main thread That means: One call stack One task at a time Example: console.log("A"); console.log("B"); console.log("C"); 👉 Output: A B C ✔ It runs one by one, not in parallel. ⚙️ Why JavaScript is single-threaded? Originally designed for browsers. Browsers (like Google Chrome) need to: Update UI Handle clicks 👉 If multiple threads changed UI at same time: UI would break Data would be inconsistent ✔ So JavaScript uses one thread → safe & predictable ⏱️ 2. What is Synchronous? 👉 Synchronous means: Code runs line by line, and each line waits for previous one to finish Example: console.log("Start"); function slowTask() { for (let i = 0; i < 1; i++) {} } slowTask(); console.log("End"); 👉 Output: Start End (after delay) ✔ End waits until slowTask finishes 🔴 Problem with synchronous nature If something takes time: Everything stops ⛔ UI freezes 👉 Bad user experience 🔄 3. Then how does JavaScript handle async? Here’s the important twist 👇 👉 JavaScript is: ✔ Single-threaded ✔ Synchronous (by default) ❗ BUT supports async using system outside JS 🌐 Behind the scenes JavaScript uses: Browser APIs Event system → Event Loop 📦 Example console.log("Start"); setTimeout(() => { console.log("Async"); }, 2000); console.log("End"); 🔄 Execution flow Start → runs setTimeout → sent to browser End → runs immediately After 2 sec → callback comes back Event loop executes it Output: Start End Async 👉 So JS looks async, but actually: It delegates work Still runs one task at a time 🧑🍳 Simple analogy You (JS) 👨🍳: Cook one dish at a time (single-threaded) Follow order (synchronous) Ask assistant to do waiting tasks (async) 👉 JavaScript is: ✔ Single-threaded One task at a time ✔ Synchronous (by default) Executes line by line ✔ Non-blocking (with help) Uses event loop + browser APIs 👉 JavaScript is single-threaded and synchronous, but uses the event loop to handle asynchronous operations without blocking execution. #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
JavaScript has two completely different systems for sharing code between files. some developers use both without knowing which one they're using - or why it is necessary to know. Every JavaScript file you've ever written that shares code with another file, uses a module system. Some developers use them daily without truly understanding what separates one from the other. Though the gap is small. The consequences of it are not. Modules are a way to break your code into separate, reusable pieces rather than writing everything in one enormous file. It makes the code clean, organised and maintainable. There are two main systems for doing this in JavaScript. And they are not the same. CommonJS: - Uses require() to bring in modules and uses module.exports to send them - It loads modules synchronously (blocks execution) - It is mostly used in older Node.js environments Example: -> Exporting module.exports = { greet: () => console.log("Hello") }; -> Importing const myModule = require('./myModule.js'); myModule.greet(); -> "Hello" How CommonJS loads: It loads synchronously - meaning JavaScript stops everything and waits for the module to fully load before moving on. This is Problematic for browsers. ES Modules (ESM): The current standard for browsers and modern Node.js. It is cleaner, more powerful, and built for performance. -> Named export export const greet = () => console.log("Hello"); -> Default export export default function greet() { console.log("Hello"); } -> Importing named import { greet } from './myModule.js'; -> Importing default import greet from './myModule.js'; Dynamic Imports ES Modules loads only what you need, only when you need it. When you hear "you're not splitting," this is what they mean. Instead of loading every module upfront - dynamic imports let you load a module on demand, only when it's actually needed. It results to a faster initial load times. ES Modules import() returns a Promise - so it works with .then() or async/await. It is also supported natively in ESM and available in CJS environments too. ES Modules aren't just a syntax choice. They're an architectural decision. The right system, used the right way, is the difference between an app that loads instantly and one that makes users wait. And users don't like to wait. So if you need your code base to be performant, you have your answer.
To view or add a comment, sign in
-
#js #10 **What is Execution Context, Call Stack and Call Back Queue in Javascript** 🧠 1. What is Execution Context? 👉 Execution Context = The environment where JavaScript code runs 📦 Types of Execution Context 1. Global Execution Context (GEC) Created when program starts Runs global code let a = 10; 👉 This runs inside Global Execution Context 2. Function Execution Context (FEC) Whenever a function is called: function greet() { console.log("Hello"); } greet(); 👉 A new execution context is created for greet() 🧩 What’s inside Execution Context? Each context has: Memory (Variables) Code (Execution) 🥞 2. What is Call Stack? 👉 Call Stack = A stack where execution contexts are stored and executed Think of it like plates stacked on top of each other 🔄 How Call Stack Works Example: function one() { two(); } function two() { console.log("Hello"); } one(); Step-by-step: Global Execution Context pushed one() called → pushed two() called → pushed console.log runs two() removed one() removed Stack flow: Call Stack: [ Global ] [ one() ] [ two() ] ← runs Then: [ Global ] 📥 3. What is Callback Queue? 👉 Callback Queue = A queue where async callbacks wait before execution Example: console.log("Start"); setTimeout(() => { console.log("Async"); }, 2000); console.log("End"); Flow: Start → runs setTimeout → goes to browser End → runs After 2 sec → callback goes to Callback Queue 🔄 How everything connects Now combine all three: 👉 Call Stack 👉 Callback Queue 👉 Event system → Event Loop 🔁 Final Flow Call Stack runs normal code Async task completes → goes to queue Event loop checks: If stack empty → move task from queue → stack 🧑🍳 Simple Analogy Execution Context = workspace 🧑💻 Call Stack = stack of tasks 📚 Callback Queue = waiting line 🚶 Event Loop = manager checking when to allow next 🎯 Quick Comparison Concept Meaning Execution Context Environment where code runs Call Stack Where functions execute Callback Queue Where async tasks wait 🧾 Final Summary Execution Context = where code runs Call Stack = manages execution order (LIFO) Callback Queue = stores async callbacks Event Loop connects everything 💡 One-line understanding 👉 JavaScript uses execution contexts inside a call stack, and async tasks wait in a callback queue until the event loop pushes them for execution. #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
𝗧𝗼𝗽𝗶𝗰 𝟭𝟮: 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 (𝗠𝗮𝗰𝗿𝗼 𝘃𝘀 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀) JavaScript is single-threaded, yet it handles thousands of concurrent operations without breaking a sweat. The secret isn't raw speed; it's an incredibly strict, ruthless prioritization engine. If you don't understand the difference between a macro and a microtask, your "asynchronous" code is a ticking time bomb for UI freezes. Summary: The Event Loop is the conductor of JavaScript's concurrency model. It continuously monitors the Call Stack and the Task Queues. To manage asynchronous work, it uses two distinct queues with vastly different priorities: Macrotasks (like setTimeout, setInterval, network events) and Microtasks (like Promises and MutationObserver). Crux: The VIP Queue: Microtasks have absolute priority. The engine will not move to the next Macrotask, nor will it allow the browser to re-render the screen, until the entire Microtask queue is completely empty. The Normal Queue: Macrotasks execute one by one. After a single Macrotask finishes, the Event Loop checks the Microtask queue again. The Starvation Risk: Because Microtasks can spawn other Microtasks, a recursive Promise chain can hold the main thread hostage, permanently blocking the UI from updating. The Deep Insight (Architect's Perspective): Traffic Control and Yielding: As architects, we must visualize the Event Loop as a traffic control system where Microtasks are emergency vehicles. When you resolve a massive chain of Promises or heavy async/await logic, you are flooding the intersection with ambulances. The browser's rendering engine—the normal traffic—is forced to sit at a red light until every single emergency vehicle has cleared. We don't just use async patterns for code readability; we must actively manage thread occupancy. For heavy client-side computations, we must intentionally interleave Macrotasks (like setTimeout(..., 0)) to force our code to yield control back to the Event Loop, allowing the browser to paint frames and keeping the UI responsive. Tip: If you have to process a massive dataset on the frontend (e.g., parsing a huge JSON file or formatting thousands of rows), do not use Promise.all on the entire set at once. That floods the Microtask queue and locks the UI. Instead, "chunk" the array and process each chunk using setTimeout or requestAnimationFrame. This gives the Event Loop room to breathe and the browser a chance to render 60 frames per second between your computation chunks. Tags: #SoftwareArchitecture #JavaScript #WebPerformance #EventLoop #FrontendEngineering #CleanCode
To view or add a comment, sign in
-
-
Symbols were the way to create private fields in JavaScript before private fields were a standard language feature. And in some cases, they're still the best option out there for performance purposes. How do they work? Instead of creating a regular string like "my-key", you create a symbol like `Symbol("my-key")`. The value that `Symbol` returns is unique, meaning that `Symbol("my-key") !== Symbol("my-key")`. This means that a developer can't access your class field using `obj[Symbol("my-key")]`. Rather, only those who have a reference to the uniquely-created symbol can access the field. Consider this code: const key = Symbol("my-key"); obj[key] = "value"; // ... export { obj }; Here, we export `obj`, but not `key`, meaning only we have the ability to read and write the value (kind of). The `ws` Node.js package has been using this clever approach for a long time. Since private fields are a native feature in JS now, there usually isn't a reason to take this approach. However, you might still find it useful when making Custom Elements, or other kinds of classes that need to use event listeners (e.g., in Node). If you remember, I made a post wayyyyyy back explaining how static event listeners provide the best performance in JavaScript. Of course, static event listeners prevent you from accessing `this`. And if you need access to a private field in your event listener, you'll be forced to use `this#key` and lose the performance boost. This is where Symbols shine! Instead of accessing private data through `this#key`, you can access it through `instance[symbolKey]`! As long as you have access to the symbol in your class's file, you'll be able to access data that the rest of the outside world can't (kind of). If you've been catching my "kind of"s, there's a caveat here: JS gives developers a way to inspect all of an object's Symbols. Generally speaking, most developers don't know about the existence of the global function that allows this, and many don't even know about Symbols at all. Plus, Symbol-based properties don't show up in IDE IntelliSense as devs type. So Symbol-based fields are semi-private! Nonetheless, Symbol-based properties are not "perfectly private". You might still choose to use them for performance purposes. But the adventurous devs who love scrutinizing code to find and use the `_DO_NOT_USE` properties will still be able to have their way. As with all things, this is about trade-offs. In my Combobox component, I've mostly been using private fields. But I've reached for Symbols in cases where I really wanted to keep using static event handlers. ComboBoxedIn Logs #17 (No, I haven't forgotten about these.)
To view or add a comment, sign in
-
🛠️ Phase 4 Complete: The "Input" Component in Pure JS Moving one step closer to a full design system! Today, I successfully implemented a versatile Input Component using only Vanilla JavaScript and CSS. Since I’m building this entire system from scratch before migrating to React, focusing on the core DOM logic for forms has been an invaluable deep dive. Key features of today’s build: 📝 State Handling: Integrated support for default, focus, error, and disabled states. 💡 Helper & Error Text: Built-in logic to toggle between validation messages and helpful hints. ⌨️ Event Integration: Added a onInput callback to handle live data binding without a framework. 🎨 Clean Architecture: Used a modular structure with input.js for logic and input.css for the design tokens. function createInput({ label = "", placeholder = "", value = "", error = "", helperText = "", disabled = false, onInput = null }) { const wrapper = document.createElement("div"); wrapper.classList.add("input-group"); // Label if (label) { const labelEl = document.createElement("label"); labelEl.classList.add("input-label"); labelEl.innerText = label; wrapper.appendChild(labelEl); } // Input const input = document.createElement("input"); input.classList.add("input-field"); input.placeholder = placeholder; input.value = value; input.disabled = disabled; // Error style if (error) { input.classList.add("input-error"); } // Event if (onInput && !disabled) { input.addEventListener("input", (e) => { onInput(e.target.value); }); } wrapper.appendChild(input); // Helper text if (helperText && !error) { const helper = document.createElement("div"); helper.classList.add("input-helper"); helper.innerText = helperText; wrapper.appendChild(helper); } // Error text if (error) { const errorText = document.createElement("div"); errorText.classList.add("input-error-text"); errorText.innerText = error; wrapper.appendChild(errorText); } return wrapper; } function renderInputPage(container) { container.innerHTML = "<h2>Inputs</h2>"; // Normal container.appendChild( createInput({ label: "Username", placeholder: "Enter username", helperText: "This will be visible publicly" }) ); // With value container.appendChild( createInput({ label: "Email", value: "test@mail.com" }) ); // Error container.appendChild( createInput({ label: "Password", placeholder: "Enter password", error: "Password must be at least 6 characters" }) ); ); } The image shows the different variants in action—from standard text fields to validation errors and disabled states. Up next: Modals and Accordions! #JavaScript #WebDevelopment #Frontend #DesignSystems #CodingJourney #VanillaJS #CSS3 #SoftwareEngineering
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