#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
Optional Chaining in JavaScript Explained
More Relevant Posts
-
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
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
🚀 Today we are going to analyse the JavaScript microtask queue, macrotask queue, and event loop. A junior developer once asked me during a code review: "Why does Node.js behave differently even when the code looks simple?" So I gave him a small JavaScript snippet and asked him to predict the output. console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); He answered confidently: Start Timeout Promise End But when we ran the code, the output was: Start End Promise Timeout He looked confused. That’s when we started analysing how JavaScript actually works internally. 🧠 Step 1: JavaScript is Single Threaded JavaScript runs on a single thread. It executes code line by line inside the call stack. So first it runs: console.log("Start") → Start console.log("End") → End Now the stack becomes empty. ⚙️ Step 2: Macrotask Queue setTimeout goes to the macrotask queue. Even though timeout is 0ms, it does not execute immediately. It waits in the macrotask queue. Examples of macrotasks: • setTimeout • setInterval • setImmediate • I/O operations • HTTP requests ⚡ Step 3: Microtask Queue Promise goes to the microtask queue. Examples of microtasks: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick (Node.js) • queueMicrotask() Microtasks always get higher priority. They execute before macrotasks. 🔁 Step 4: Event Loop Now the event loop starts working. The event loop checks: Is the call stack empty? Yes Check microtask queue Execute all microtasks Then execute macrotasks So execution becomes: Start End Promise Timeout Now everything makes sense. 🏗️ Real Production Example Imagine a Node.js API: app.get("/users", async (req, res) => { console.log("Request received"); setTimeout(() => console.log("Logging"), 0); await Promise.resolve(); console.log("Processing"); res.send("Done"); }); Execution order: Request received Processing Logging Why? Because Promise (microtask) runs before setTimeout (macrotask). This directly affects: • API response time • Logging • Background jobs • Queue processing • Performance optimization 🎯 Why Every Node.js / NestJS / Next.js Developer Should Know This Because internally: • Async/Await uses Promises • API calls use Event Loop • Background jobs use Macrotasks • Middleware uses Microtasks • Performance depends on queue execution Without understanding this, debugging production issues becomes very difficult. 💡 Final Thought JavaScript is not just a language. It is an event-driven execution engine. If you understand microtask queue, macrotask queue, and event loop, you don’t just write code — you understand how the runtime thinks. And once you understand the runtime, you start building faster and more scalable systems. #JavaScript #NodeJS #EventLoop #Microtasks #Macrotasks #NextJS #NestJS #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 setTimeout() vs setInterval() in JavaScript 📘 Definition: setTimeout() is a built-in JavaScript function that executes a given function once after a specified delay (in milliseconds). 👉 Syntax: setTimeout(callbackFunction, delay); 👉 Example: setTimeout(() => { console.log("Runs after 2 seconds"); }, 2000); Key Points: ✔ Executes only once ✔ Delay is in milliseconds (1000ms = 1 second) ✔ Time is not exact, it's a minimum delay 📘 Definition: setInterval() is a built-in JavaScript function that repeatedly executes a function at fixed time intervals. 👉 Syntax: setInterval(callbackFunction, interval); 👉 Example: setInterval(() => { console.log("Runs every 2 seconds"); }, 2000); Key Points: ✔ Executes again and again ✔ Runs at a fixed interval ✔ Continues until manually stopped 🧠 How JavaScript Handles Them (Event Loop Concept) JavaScript is single-threaded, meaning it can execute one task at a time. So how does it handle timers? 👉 Flow: >>>setTimeout / setInterval are handled by Browser APIs >>>After delay, callbacks go to the Callback Queue >>>The Event Loop moves them to the Call Stack when it’s empty That’s why: 👉 Execution time is not guaranteed 👉 It depends on what’s already running ⚠️ Important Difference ✔ setTimeout → Executes once after delay ✔ setInterval → Executes repeatedly at intervals ⚠️ Common Issue with setInterval() If the function takes longer than the interval: >> Calls can overlap >> Performance issues may occur 💡 Better Alternative (Advanced Concept) Using recursive setTimeout() function runTask() { setTimeout(() => { console.log("Controlled execution"); runTask(); }, 2000); } runTask(); ✔ Ensures next execution starts after previous finishes ✔ Gives better control 🛑 Stopping Timers: const id = setInterval(() => { console.log("Running..."); }, 1000); clearInterval(id); Use: ✔ clearTimeout() to stop timeout ✔ clearInterval() to stop interval Real-World Use Cases 🔹 setTimeout(): Delayed popups, API retry logic , Debouncing inputs 🔹 setInterval(): Digital clocks , Live dashboards, Polling servers #JavaScript #AsyncJS #EventLoop #FrontendDevelopment #Coding #WebDevelopment
To view or add a comment, sign in
-
#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
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
-
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
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
To view or add a comment, sign in
-
In a Javascript L1 & L2 round the following questions can be asked from interviewer. 1. What is the difference between 'Pass by Value' and 'Pass by Reference'? 2. What is the difference between map and filter ? 3. What is the difference between map() and forEach() 4. What is the difference between Pure and Impure functions? 5. What is the difference between for-in and for-of ? 6. What are the differences between call(), apply() and bind() ? 7. List out some key features of ES6 ? 8. What’s the spread operator in javascript ? 9. What is rest operator in javascript ? 10. What are DRY, KISS, YAGNI, SOLID Principles ? 11. What is temporal dead zone ? 12. Different ways to create object in javascript ? 13. Whats the difference between Object.keys,values and entries 14. Whats the difference between Object.freeze() vs Object.seal() 15. What is a polyfill in javascript ? 16. What is generator function in javascript ? 17. What is prototype in javascript ? 18. What is IIFE ? 19. What is CORS ? 20. What are the different datatypes in javascript ? 21. What are the difference between typescript and javascript ? 22. What is authentication vs authorization ? 23. Difference between null and undefined ? 24. What is the output of 3+2+”7” ? 25. Slice vs Splice in javascript ? 26. What is destructuring ? 27. What is setTimeOut in javascript ? 28. What is setInterval in javascript ? 29. What are Promises in javascript ? 30. What is a callstack in javascript ? 31. What is a closure ? 32. What are callbacks in javascript ? 33. What are Higher Order Functions in javascript ? 34. What is the difference between == and === in javascript ? 35. Is javascript a dynamically typed language or a statically typed language 36. What is the difference between Indexeddb and sessionstorage ? 37. What are Interceptors ? 38. What is Hoisting ? 39. What are the differences let, var and const ? 41. Differences between Promise.all, allSettled, any, race ? 42. What are limitations of arrow functions? 43. What is difference between find vs findIndex ? 44. What is tree shaking in javascrip 45. What is the main difference between Local Storage and Session storage 46. What is eval() 47. What is the difference between Shallow copy and deep copy 48. What are the difference between undeclared and undefined variables 49. What is event bubbling 50. What is event capturing 51. What are cookies 52. typeOf operator 53. What is this in javascript and How it behaves in various scenarios 54. How do you optimize the performance of application 55. What is meant by debouncing and throttling 𝐠𝐞𝐭 𝐞𝐛𝐨𝐨𝐤 𝐰𝐢𝐭𝐡 (detailed 232 ques = 90+ frequently asked Javascript interview questions and answers, 90+ Reactjs Frequent Ques & Answers, 50+ Output based ques & ans, 23+ Coding Questions & ans, 2 Machine coding ques & ans) 𝐄𝐛𝐨𝐨𝐤 𝐋𝐢𝐧𝐤: https://lnkd.in/gJMmH-PF Follow on Instagram : https://lnkd.in/gXTrcaKP #javascriptdeveloper #reactjs #reactnative #vuejsdeveloper #angular #angulardeveloper
To view or add a comment, sign in
-
Day 4: Why doesn't JavaScript get confused? 🧩 Variable Environments & The Call Stack(How Functions works in JS) Today I explored how JavaScript handles multiple variables with the same name across different functions. Using the code below, I took a deep dive into the Variable Environment and the Call Stack. 💻 The Code Challenge: javascript var x = 1; a(); b(); console.log(x); function a() { var x = 10; console.log(x); } function b() { var x = 100; console.log(x); } 🧠 The "Behind the Scenes" Logic: 1️⃣ Global Execution Context (GEC): Memory Phase: x is set to undefined. Functions a and b are stored entirely. Execution Phase: x becomes 1. Then, a() is invoked. 2️⃣ The Function a() Context: A brand new Execution Context is created and pushed onto the Call Stack. This context has its own Variable Environment. The x inside here is local to a(). It logs 10, then the context is popped off the stack and destroyed. 3️⃣ The Function b() Context: Same process! A new context is pushed. Its local x is set to 100. It logs 100, then it's popped off the stack. 4️⃣ Back to Global: Finally, the last console.log(x) runs in the Global context. It looks at the GEC’s Variable Environment where x is still 1. 📚 Key Learnings: Variable Environment: Each execution context has its own "private room" for variables. The x in a() is completely different from the x in the Global scope. Call Stack: It acts as the "Manager," ensuring the browser knows exactly which execution context is currently running. Independence: Functions in JS are like mini-programs with their own memory space. This is the foundation for understanding Lexical Scope and Closures! Watching this happen live in the browser's "Sources" tab makes you realize that JS isn't "magic"—it's just very well-organized! 📂 #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingTips #FrontendEngineer #CodingLogic
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