🚀 How JavaScript Actually Works — In Depth (Execution Context, Call Stack & More). Let’s break it down step by step. 🔹 1. JavaScript Is Single-Threaded — But Asynchronous JavaScript has: • One main thread • One Call Stack • But it can still handle asynchronous operations efficiently This is possible because of the JavaScript Runtime Environment, which includes: • Call Stack • Heap Memory • Web APIs (in browsers) • Callback Queue • Microtask Queue • Event Loop 🔹 2. Global Execution Context (GEC) Is Created First When your JavaScript file starts running, the very first thing created is the Global Execution Context, which has two phases: ✅ Phase 1 — Memory Creation (Hoisting Phase) JavaScript scans the entire code and allocates memory for: • Variables → stored as undefined • Functions → stored with full function definition Example: console.log(name); var name = "Raj"; function greet() { console.log("Hello"); } During memory phase: • name → allocated as undefined • greet → stored as actual function This is why console.log(name) prints undefined and not an error. 🔹 3. Phase 2 — Code Execution Phase Now JavaScript starts executing line by line. • console.log(name) → prints undefined • Then name = "Raj" is assigned • Functions execute only when called 🔹 4. Function Execution Context (FEC) Whenever a function is called, a new Execution Context is created on top of the Call Stack. Example: function add(a, b) { return a + b; } add(5, 10); Steps: Global Execution Context exists add(5,10) is called New Execution Context for add() is created It has: • Its own memory space • Its own variables • Its own return value Once the function finishes, its execution context is removed from the Call Stack. 🔹 5. Call Stack — The Heart of JavaScript Execution The Call Stack follows LIFO (Last In, First Out). Example: function first() { second(); } function second() { third(); } function third() { console.log("Done"); } first(); Call Stack Flow: • first() pushed • second() pushed • third() pushed • third() completes → popped • second() completes → popped • first() completes → popped 🔹 6. How Asynchronous Code Runs (Event Loop) Example: console.log("Start"); setTimeout(() => { console.log("Inside Timeout"); }, 0); console.log("End"); Execution Order: "Start" prints setTimeout goes to Web APIs "End" prints Callback goes to Callback Queue Event Loop moves it to Call Stack "Inside Timeout" prints Even with 0ms, it runs after synchronous code. 🔹 7. Microtasks vs Macrotasks Microtasks (higher priority): • Promises • MutationObserver Macrotasks: • setTimeout • setInterval Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Because Microtasks run before Macrotasks. #JavaScript #WebDevelopment #Frontend #NodeJS #EventLoop #ExecutionContext #SoftwareEngineering #Programming #JSMastery
JavaScript Execution Context, Call Stack & Event Loop Explained
More Relevant Posts
-
⚙️ JavaScript – Execution Context & Event Loop Understanding How JavaScript Works Internally JavaScript looks simple on the surface, but internally it follows a well-defined execution process. Understanding this helps you write better code and answer interview questions confidently. 🔹 What Is Execution Context? An execution context is the environment where JavaScript code is executed. There are three types: Global Execution Context Function Execution Context Eval Execution Context (rarely used) 🔹 Global Execution Context This is created when the JavaScript file runs. It contains: Global variables Global functions this keyword (refers to window in browsers) 👉 Created only once. 🔹 Function Execution Context Created whenever a function is called. It contains: Function arguments Local variables Inner functions Each function call creates a new execution context. 🔹 Execution Context Phases Every execution context has two phases: 1️⃣ Memory Creation Phase Variables are allocated memory Functions are stored completely Variables are initialized with undefined 2️⃣ Execution Phase Code is executed line by line Values are assigned Functions are invoked 👉 This explains hoisting. 🔹 Call Stack The call stack keeps track of execution contexts. Stack follows LIFO (Last In, First Out) Global context is at the bottom Function contexts are added and removed as needed Example: function one() { two(); } function two() { console.log("Hello"); } one(); 👉 two() is pushed, executed, then popped 👉 Then one() finishes 🔹 What Is the Event Loop? JavaScript is single-threaded, but it handles async operations using the event loop. The event loop continuously checks: Call Stack Callback Queue Microtask Queue 🔹 Web APIs Browser provides Web APIs for async tasks: setTimeout fetch DOM events These tasks run outside the call stack. 🔹 Callback Queue Holds callbacks from: setTimeout Event listeners Executed only when call stack is empty. 🔹 Microtask Queue Holds: Promise callbacks (then, catch) async / await 👉 Microtasks have higher priority than callback queue. 🔹 Event Loop Flow (Simple) Execute synchronous code Async tasks go to Web APIs Microtasks are executed first Callback queue executes next 👉 This explains async behavior clearly. 🧠 Simple Way to Remember Execution Context → where code runs Call Stack → manages execution Web APIs → handle async work Microtask Queue → promises first Callback Queue → timers & events Event Loop → manages everything ✅ Why Execution Context & Event Loop Matter Explains async JavaScript behavior Helps debug complex issues Very important for interviews Makes React & backend concepts easier Without this knowledge, async feels confusing. With this knowledge, everything clicks 🔥 #JavaScript #EventLoop #ExecutionContext #WebDevelopment #FrontendDevelopment #LearningInPublic #FullStackJourney
To view or add a comment, sign in
-
-
🔁 JavaScript Event Loop & Queues - Explained Once and For All Ever wondered how JavaScript handles multiple tasks while being single-threaded? The answer is the Event Loop and its Queues. If you truly understand this, you understand asynchronous JavaScript. Let’s break it down no fluff, no gaps. 🧠 First, One Important Truth JavaScript is single-threaded. ➡️ It can execute only one task at a time on the Call Stack. Yet we still do: - API calls - timers - promises - user interactions How? 👉 Because of the Event Loop + Queues + Web APIs 🧩 The Main Building Blocks 1️⃣ Call Stack (Execution Stack) - Where synchronous code runs - Functions are pushed → executed → popped - If the stack is busy, nothing else runs 📌 JavaScript executes everything here, one by one. 2️⃣ Web APIs (Browser / Runtime) Not part of JavaScript itself. Handles: - setTimeout - setInterval - fetch - DOM events - addEventListener 📌 Async operations are sent here to wait. 3️⃣ Queues (Very Important) JavaScript has multiple queues, not just one. 🔹 a) Microtask Queue (Highest Priority) Contains: - Promise.then / catch / finally - queueMicrotask - MutationObserver 📌 Always executed before the callback queue. 🔹 b) Callback Queue (Macrotask Queue) Contains: - setTimeout - setInterval - DOM events - Message events 📌 Executed only when the call stack & microtasks are empty. 🔄 4️⃣ The Event Loop (The Orchestrator) The Event Loop continuously checks: 1. Is the Call Stack empty? 2. If yes → Execute ALL Microtasks 3. Then → Take ONE task from Callback Queue 4. Repeat forever ♾️ 📌 This is why promises often run before timers. ⚡ Execution Order Rule (Golden Rule) Call Stack → Microtask Queue (ALL) → Callback Queue (ONE) → Repeat 🧪 Example (Read Carefully) -------------------------------------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); -------------------------------------------------------- 🧠 Execution Flow 1. Start → Call Stack 2. setTimeout → Web API → Callback Queue 3. Promise.then → Microtask Queue 4. End → Call Stack 5. Call Stack empty → Run Microtasks 6. Then → Run Callback Queue ✅ Output Start End Promise Timeout 🤯 Common Misconceptions (Very Important) ❌ setTimeout(fn, 0) runs immediately ✅ It runs after microtasks ❌ JavaScript is multi-threaded ✅ JavaScript is single-threaded, runtime is not ❌ Promises are faster ✅ Promises have higher priority, not faster execution If you master this, async bugs stop feeling “random”. 🧠 One-Line Summary "The Event Loop decides when your async code runs, not how fast it runs." If this explanation helped you finally “see” the Event Loop clearly, 👍 like | 🔁 share | 💬 comment #JavaScriptInternals #JSConcepts #WebPerformance #BrowserInternals #AsyncProgramming
To view or add a comment, sign in
-
-
⚡ JavaScript – Async JavaScript & APIs Handling Time-Consuming Tasks Efficiently JavaScript is single-threaded, but real applications need to handle: Server requests API calls Background operations Async JavaScript allows these tasks to run without blocking the UI. 🔹 What Is Asynchronous JavaScript? Asynchronous code runs in the background while the rest of the program continues. Examples: Fetching data from a server Reading files Timers (setTimeout) JavaScript handles this using callbacks, promises, and async/await. 🔹 Callbacks A callback is a function passed as an argument to another function, executed later. function getData(callback) { setTimeout(() => { callback("Data received"); }, 1000); } getData((data) => { console.log(data); }); 👉 Problem: Too many callbacks lead to callback hell 👉 Hard to read and maintain 🔹 Promises A Promise represents a value that will be available later. States of a Promise: Pending Fulfilled Rejected const promise = new Promise((resolve, reject) => { resolve("Success"); }); promise .then(result => console.log(result)) .catch(error => console.log(error)); 👉 Solves callback nesting 👉 Cleaner than callbacks 🔹 async / await A modern and cleaner way to handle promises. async function getData() { const result = await promise; console.log(result); } 👉 Looks like synchronous code 👉 Easier to read and debug 👉 Most used in modern JavaScript & React 🔹 Fetch API Used to request data from a server or API. fetch("https://lnkd.in/gBVe_Q-K") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)); Using async / await: async function fetchData() { const response = await fetch(url); const data = await response.json(); console.log(data); } 🔹 Working with APIs (Intro) APIs provide data from the backend, usually in JSON format. Used for: User data Product lists Dashboards Weather apps Frontend → consumes APIs Backend → provides APIs 🧠 Simple Way to Remember Callback → function runs later Promise → future value async / await → clean promise handling Fetch → get data from server API → bridge between frontend & backend ✅ Why Async JavaScript & APIs Matter Prevents UI freezing Essential for real-world applications Core concept for React, Node.js Frequently asked in interviews Without async code, apps feel slow. With async code, apps feel smooth. 🎯 Key Takeaway Async JavaScript & APIs prepare you for backend development and React. Master this, and you’re ready for real-world web applications 🚀 #JavaScript #AsyncJavaScript #APIs #WebDevelopment #FrontendDevelopment #Backend #LearningInPublic
To view or add a comment, sign in
-
-
JavaScript Event Loop, Microtasks, and Macrotasks Event Loop Overview The event loop is JavaScript's mechanism for handling asynchronous operations. It's what enables JavaScript to be non-blocking despite being single-threaded javascript console.log('1. Start'); setTimeout(() => console.log('2. Timeout'), 0); Promise.resolve().then(() => console.log('3. Promise')); console.log('4. End'); // Output order: // 1. Start // 4. End // 3. Promise // 2. Timeout Microtasks vs Macrotasks Macrotasks (Tasks): What they are: Larger, independent tasks Examples: setTimeout, setInterval setImmediate (Node.js) I/O operations UI rendering (browser) requestAnimationFrame (browser) Queue: Macrotask Queue (Task Queue) Microtasks: What they are: Smaller, high-priority tasks Examples: Promise callbacks (.then(), .catch(), .finally()) queueMicrotask() MutationObserver (browser) process.nextTick() (Node.js - has even higher priority) Queue: Microtask Queue (Job Queue) Execution Order Rules: console.log('Script start'); setTimeout(() => { console.log('setTimeout'); }, 0); Promise.resolve() .then(() => { console.log('Promise 1'); }) .then(() => { console.log('Promise 2'); }); console.log('Script end'); /* Execution Order: 1. Script start 2. Script end 3. Promise 1 4. Promise 2 5. setTimeout */ Key Execution Flow: Execute all synchronous code Process ALL microtasks in the queue Render (if browser) Process ONE macrotask Repeat from step 2 Visualizing the Event Loop text ┌───────────────────────────┐ │ Call Stack │ └─────────────┬─────────────┘ │ ┌─────────────▼───────┐ │ Event Loop (Monitors) │ └───────────┬──────────┘ │ ┌─────────┴───── ┐ │ │ ┌───▼──┐ ┌─── ▼──┐ │ Micro │ │ Macro │ │ Tasks │ │ Tasks │ │ Queue │ │ Queue │ └───────┘ └──────── ┘ Practical Implications 1. Microtasks Block Rendering // This will freeze the UI function freezeUI() { Promise.resolve().then(() => { freezeUI(); // Infinite microtask loop }); } // freezeUI(); // Warning: Don't run this! 2. Proper Task Scheduling // ❌ Poor practice - might block UI function processHeavyData() { for (let i = 0; i < 1000000; i++) { Promise.resolve().then(() => { // Heavy computation in microtask }); } } // ✅ Better - yields to browser rendering function processHeavyDataBetter() { function chunkedProcess(start) { for (let i = start; i < start + 1000; i++) { // Process chunk } if (start < 1000000) { // Use macrotask to allow rendering setTimeout(() => chunkedProcess(start + 1000), 0); } } chunkedProcess(0); } Best Practices Use microtasks for immediate async operations // Defer non-critical work //Avoid microtask recursion
To view or add a comment, sign in
-
-
🚀 Deep Dive into JavaScript Arrays: 📦 Packed vs 🕳️ Holey Elements (V8 Engine Internals) JavaScript arrays look simple on the surface, but under the hood their structure has a direct impact on performance. Most developers use arrays daily, yet very few are aware of how JavaScript engines optimize (or de-optimize) them. If you are working on performance-sensitive applications or preparing for technical interviews, this is a concept worth understanding. 🔍 How V8 Classifies Arrays Modern JavaScript engines like V8 categorize arrays based on two key factors: • Type of elements (integers, floating-point numbers, mixed types) • Continuity of indexes (whether indexes are sequential or contain gaps) ✅ Packed Arrays (Optimized & Fast) Packed arrays have continuous indexes with no gaps, allowing the engine to store them efficiently and access elements quickly. 👉 PACKED_SMI_ELEMENTS (Only Integers) const arr = [1, 2, 3, 4, 5]; 👉 PACKED_DOUBLE_ELEMENTS (Floating Numbers) const arr = [1, 2, 3, 4, 5.45, 6.0]; 👉 PACKED_ELEMENTS (Mixed Types) const arr = [1, 2, 3.5, 'a', true]; ⚠ Holey Arrays (De-optimized) Holey arrays contain missing indexes (holes). This forces the engine to perform additional checks during access, which reduces performance. 👉 HOLEY_SMI_ELEMENTS (Integers with Gaps) const arr = [1, 2, 3, , , 6]; 👉 HOLEY_DOUBLE_ELEMENTS (Floating Numbers with Gaps) const arr = [1.2, 2.5, , , 5.45, 6.0]; 👉 HOLEY_ELEMENTS (Mixed Types with Gaps) const arr = [1, 2, 3.5, 'a', , , true]; Another common way holey arrays are created: const arr = []; arr[0] = 1; arr[5] = 6; ⚠ Important Note Once an array becomes Holey, the JavaScript engine cannot re-optimize it back to a Packed array, even if the missing indexes are later filled. Also avoid using let myArr = new Array(5); because it creates an array that appears like let arr = [undefined, undefined, undefined, undefined, undefined]; ✅ Better Alternatives (Packed Arrays) If you want a fixed-size array with initialized values, use: 👉 let arr = new Array(5).fill(0); 👉 let arr = Array.from({ length: 5 }, () => 0); Understanding how the engine handles arrays helps you write better-performing, more predictable code, and it’s the kind of detail that quietly sets you apart in interviews and code reviews. ✨ #JavaScript #V8 #V8Debugger #WebDevelopment #FrontendDevelopment #NodeJS #PerformanceOptimization #JavaScriptInternals #SoftwareEngineering #InterviewPreparation #SoftwareDeveloper #SoftwareEngineer #JavaScriptDebugging #ChromeDevTools #NodeJSDebugging #JavaScriptEngine
To view or add a comment, sign in
-
𝗖𝗼𝗿𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 & 𝗟𝗮𝗻𝗴𝘂𝗮𝗴𝗲 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 1. What is the difference between var, let, and const? (temporal dead zone, block scoping, re-declaration, re-assignment) 2. Explain hoisting in JavaScript. How does it behave differently with var, function, let and const? 3. What are closures in JavaScript? Give a practical example where closures are useful. 4. How does the this keyword work in JavaScript? Explain its value in different contexts (global, object method, constructor, arrow function, event handler, strict mode). 5. What is the difference between == and ===? When does type coercion happen and what are some surprising coercion results? 6. Explain null vs undefined vs void 0. When would you intentionally return null vs undefined? 7. What are the different data types in JavaScript? What is the difference between primitive and reference types? 8. How can you reliably check the type of a value in JavaScript? (typeof, instanceof, Object.prototype.toString, Array.isArray, etc.) 9. What is coercion? Give examples of implicit and explicit coercion. 10. Explain the difference between ==, ===, Object.is(), and SameValueZero. 11. What is an IIFE? Why was it commonly used before let/const and modules? 12. What are arrow functions? How do they differ from regular functions (regarding this, arguments, super, constructor behavior)? 13. What are higher-order functions? Name at least 5 built-in examples. 14. Explain the difference between function declaration, function expression, and arrow function expression. 15. What is the arguments object? Why is it usually better to use rest parameters (…args) instead? 16. What is the Event Loop? Explain the call stack, task queue (macrotask), microtask queue, and rendering phase. 17. What is the difference between macrotasks and microtasks? Give examples of each. 18. Explain how setTimeout(…, 0) really works. 19. Compare setTimeout vs setInterval. When would one be preferred over the other? 20. What are Promises? Explain the states (pending, fulfilled, rejected) and the .then/.catch/.finally chain. 21. What do Promise.all, Promise.allSettled, Promise.any, Promise.race do? When would you use each? 22. How does async/await work under the hood? Is it just syntactic sugar? 23. How can you handle errors properly with async/await? (try/catch vs .catch) 24. What happens if you forget to await an async function? 25. How would you run multiple promises concurrently but still keep good error handling? For help and guidance in you carrier path https://lnkd.in/gH3paVi7 Join my dev community for resources📚, tech talks🧑🏻💻and learning 🧠 https://lnkd.in/gt8WeZSt #React #AI #Frontend #WebDevelopment #CareerGrowth #EngineeringMindset
To view or add a comment, sign in
-
⚡ JavaScript Performance Myths That Are Still Slowing Down Real Applications JavaScript engines (V8, SpiderMonkey, JavaScriptCore) are highly optimized. Yet many apps feel slow because developers optimize the wrong things. Let’s break more performance myths — and what actually matters instead. ❌ Myth 1: “Classic for-loops are always faster” Modern engines aggressively optimize map, filter, and reduce. ✔ Focus on clarity first, optimize only after profiling. ❌ Myth 2: “Async/Await hurts performance” async/await compiles down to Promises. ✔ The real issue is unnecessary async boundaries and sequential awaits. ❌ Myth 3: “Frameworks are the reason my app is slow” Most slowness comes from: • Excessive re-renders • Large component trees • Poor state design ✔ Optimize render frequency, not the framework. ❌ Myth 4: “Debounce/Throttle are micro-optimizations” Uncontrolled event handlers can trigger hundreds of executions per second. ✔ Always debounce search, scroll, resize, and input events. ❌ Myth 5: “JavaScript doesn’t have memory leaks” Closures, timers, event listeners, and globals absolutely leak memory. ✔ Clean up listeners and intervals, especially in SPA lifecycles. ❌ Myth 6: “Bigger Bundles Only Affect Load Time” Large bundles also slow: • Parsing • Compilation • Runtime execution ✔ Code-splitting improves both load and runtime performance. ❌ Myth 7: “JSON.stringify / parse are cheap” They are expensive for large objects. ✔ Avoid deep serialization in hot paths and frequent state updates. ❌ Myth 8: “Re-rendering is cheap” Re-renders trigger reconciliation, diffing, and sometimes layout thrashing. ✔ Use memoization strategically (memo, useMemo, useCallback). ❌ Myth 9: “setTimeout fixes performance issues” Deferring work doesn’t reduce cost — it just shifts it. ✔ Break heavy tasks using requestIdleCallback or Web Workers. ❌ Myth 10: “Premature optimization is always bad” Ignoring known hot paths is just as dangerous. ✔ Measure first, then optimize intentionally. ✅ What Actually Improves JavaScript Performance • Profiling with DevTools • Reducing render frequency • Smarter async design • Efficient data structures • Memory lifecycle awareness 🚀 Performance is not about clever tricks. It’s about understanding how JavaScript actually runs. What’s the most surprising performance issue you’ve debugged? #JavaScript #WebPerformance #Frontend #NodeJS #ReactJS #Optimization #CleanCode #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 2015, JavaScript did not have a way to create private object properties. Developers used tricks like prefixes or closures to manage uniqueness. The introduction of Symbols solved this problem. A Symbol is a unique identifier created using the Symbol() function. Here are some key Well-Known Symbols: - Symbol.hasInstance: customizes the instanceof operator behavior - 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 impact performance. Using Symbols can incur a cost, especially when abstracting data structures or heavy computational tasks. Many modern frameworks and libraries use Well-Known Symbols for internal management. For example, React and Vue use Symbols to handle component states uniquely. To debug issues with Well-Known Symbols, you can use console logging and debugging tools like Chrome DevTools. Source: https://lnkd.in/d_8if4qz
To view or add a comment, sign in
-
🔑 Prototype & Inheritance in JavaScript 1. Prototype Chain Every JavaScript object has a hidden property called [[Prototype]]. When you try to access a property that doesn’t exist on the object itself, JavaScript looks up the prototype chain to find it. Example: const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new When you use the new keyword, JavaScript creates a new object and links it to the constructor’s prototype. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const varun = new Person("Varun"); console.log(varun.greet()); // Hello, Varun 3. ES6 Classes (Syntactic Sugar) JavaScript classes are just syntactic sugar over prototype-based inheritance. They make the code cleaner and more readable, but under the hood, they still use prototypes. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. 📌 Quick Interview Tip Interviewers often ask: “Explain the prototype chain.” “What’s the difference between class inheritance and prototype inheritance?” “Why are methods added to the prototype instead of inside the constructor?” const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new Jab tum new keyword use karte ho, ek naya object banata hai jo constructor ke prototype se link hota hai. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const champ= new Person("Champ"); console.log(champ.greet()); // Hello, Champ 3. ES6 Classes (syntactic sugar) Classes JS me bas prototype-based inheritance ka cleaner syntax hain. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. #React #ReactJS #Frontend #WebDevelopment #JavaScript #Interviews #SoftwareEngineering #infy
To view or add a comment, sign in
-
🔍 JavaScript Objects: Dot Notation vs Bracket Notation Why do we have two ways to access object properties — and when should we use each? If both dot notation and bracket notation do the same thing, why does JavaScript even support both? The short answer: flexibility + real-world use cases. Let’s break it down 👇 ⸻——————————————————- 1️⃣ Dot Notation – Clean, readable, and predictable const user = { name: "Jagdish", role: "Frontend Developer" }; user.name; // "Jagdish" ——————————————- ✅ When to use dot notation • Property names are known at development time • Keys are valid JavaScript identifiers • You want clean & readable code 🚫 When you can’t use dot notation user.first-name ❌ // Error user["first-name"] ✅ Why? Dot notation does not support: • Spaces • Hyphens (-) • Dynamic values —————————————————— 2️⃣ Bracket Notation – Dynamic and powerful const key = "role"; user[key]; // "Frontend Developer" ✅ When to use bracket notation • Property name is dynamic • Key comes from user input, API response, or loop • Property contains special characters ———————————— const data = { "total-users": 120, "2025": "Active" }; data["total-users"]; // 120 data["2025"]; // "Active" —————————————- Dot notation fails here ❌ Bracket notation works perfectly ✅ _______________________________ 3️⃣ Real-world examples 🔹 API responses response.data[fieldName]; You don’t know the key beforehand → bracket notation is required. 🔹 Forms & dynamic filters filters[selectedFilter]; 🔹 Looping through objects for (let key in user) { console.log(user[key]); } Dot notation simply cannot work here. ——————————————————————- 4️⃣ Mental model to remember forever 🧠 • Dot notation → Static & known • Bracket notation → Dynamic & unknown If JavaScript needs to evaluate the key at runtime, you must use bracket notation. JavaScript didn’t give us two notations by accident. It gave us simplicity and power. Knowing why and when to use each is what separates 👉 someone who knows syntax from 👉 someone who understands JavaScript deeply. If this helped you, react or share — someone in your network needs this today 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #JavaScriptTips #CodingBestPractices #LearnJavaScript #SoftwareEngineering #CleanCode #DeveloperCommunity #ProgrammingConcepts #TechCareers #ReactJS #WebDev
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