Closures in JavaScript — Full Bollywood Vibes Edition 🍿 In JavaScript, Closure is like that mystery character in a movie — quiet at first, but once you understand it, you realize, “picture toh ab samajh mein aayi!” 😎 Let’s break it down with some filmy style 👇 --- 💡 What is a Closure? Closure is when a function remembers its lexical scope — even after the outer function has finished execution. Or simply put: > “Jo baat andar hoti hai, wo andar hi rehti hai!” (— Gangs of Wasseypur vibes) 😜 Example 👇 function makeHero(name) { return function dialogue() { console.log(`${name} — kabhi kabhi lagta hai apun hi bhagwan hai!`); }; } const hero = makeHero("Hemant"); hero(); // Hemant — kabhi kabhi lagta hai apun hi bhagwan hai! Even after makeHero finishes, the inner function still remembers name. That memory = Closure! 🧠 --- 🎭 Closures Are Everywhere! When you use: setTimeout event listeners callback functions or React hooks (useState/useEffect) Closures are silently doing their work behind the scenes! Just like a background character holding the movie together without getting the spotlight 🎥 > “Main hoon na… bas dikhta nahi hoon.” (— SRK style) 😅 --- ⚙️ Another Example — Private Variables Closures help you create private data 👇 function bankAccount() { let balance = 1000; return { deposit(amount) { balance += amount; console.log(`Balance: ₹${balance}`); }, withdraw(amount) { balance -= amount; console.log(`Balance: ₹${balance}`); }, }; } const myAcc = bankAccount(); myAcc.deposit(500); // ₹1500 myAcc.withdraw(200); // ₹1300 Here, balance can’t be accessed directly — it’s safe inside the closure 🔒 > “Jo andar gaya, wo bahar nahi aata.” (— Hera Pheri energy 💸) --- 💬 In short: Closures = Memory + Power They let your inner functions remember data long after the scene is over. Or as our hero would say: > “Don ko pakadna mushkil hi nahi… impossible hai!” — And same goes for understanding JS deeply without knowing closures 😉 --- #JavaScript #Closures #WebDevelopment #CodingHumor #Frontend #LearningIsFun #Bollywood
Understanding Closures in JavaScript with a Bollywood Twist
More Relevant Posts
-
Here’s a cool topic that’s gaining real traction for JavaScript developers—and one that often surprises even seasoned engineers: the power of the Temporal API for modern date and time handling. --- \*\*Why Temporal Could Be Your New Best Friend for Date/Time in JavaScript\*\* If you've ever wrestled with JavaScript’s built-in Date object, you know the pain: timezone quirks, daylight saving adjustments, inconsistent parsing, and messy APIs that make even simple tasks feel complicated. Enter the Temporal API—a brand-new global object designed to finally fix these problems with modern date/time handling. Temporal provides \*\*immutable\*\* and \*\*well-defined objects\*\* for dates, times, time zones, and durations. It’s a game-changer for anyone building apps that rely on time calculations or scheduling. --- ### What makes Temporal so great? 1. \*\*Clear intent with types\*\*: Unlike the Date object that mixes date, time, and timezone info all in one, Temporal separates those concerns into different classes such as `PlainDate`, `PlainTime`, `ZonedDateTime`, and `Duration`. That means less guesswork and bugs. 2. \*\*Better timezone support\*\*: Handling timezones and daylight saving time is notoriously tricky, but `ZonedDateTime` wraps this complexity so you don’t have to manually adjust offsets. 3. \*\*Immutable and chainable\*\*: Temporal objects are immutable, so whenever you "change" them, you get new instances. This makes reasoning about your code and debugging far easier. 4. \*\*Human-readable and precise\*\*: You can create, add, subtract, and compare dates easily with intuitive methods, avoiding unexpected edge cases that plague the old Date API. --- ### Quick example: ```js // Creating a ZonedDateTime for a specific timezone const datetime = Temporal.ZonedDateTime.from\("2024-06-17T10:00:00-07:00\[America/Los\_Angeles\]"\); // Let's say you want to add 3 days and 4 hours const newDateTime = datetime.add\(\{ days: 3, hours: 4 \}\); console.log\(newDateTime.toString\(\)\); // Outputs: 2024-06-20T14:00:00-07:00\[America/Los\_Angeles\] ``` Check out the Temporal API if your projects involve scheduling, calendar apps, or any complex date/time logic. It’s coming to browsers and Node.js soon, and polyfills are already available. Say goodbye to the old Date headaches and hello to more reliable, readable, and maintainable time code. --- If you haven’t looked into Temporal yet, now's a perfect time. Your future self \(and your code reviews\) will thank you! #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #TechInnovation #Frontend #DateTime #Programming
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree 🧠 Understanding Scope in JavaScript — The Rulebook for Variables! Ever seen this error? ❌ “x is not defined” That’s when Scope comes into the picture 🌿 Let’s simplify it 👇 ⚙️ What is Scope? - Think of scope as a playground boundary 🎯 - It decides where your variables can be accessed in your code. - If you declare a variable inside a certain boundary (like inside a function), you can’t access it outside — just like you can’t play outside the playground fence! 🏞️ 🌍 1️⃣ Global Scope - Variables declared outside any function or block live in the global world 🌎 - They can be accessed from anywhere in the code. var name = "Virashree"; function greet() { console.log("Hello " + name); } greet(); // ✅ Accessible console.log(name); // ✅ Accessible 💡 Anything defined globally stays accessible everywhere. But be careful — too many globals can cause conflicts in big projects! 🌿 2️⃣ Function Scope - Variables declared inside a function are only accessible inside that function. function greet() { var message = "Hello from inside!"; console.log(message); // ✅ Works } greet(); console.log(message); // ❌ ReferenceError 🎯 JS keeps message private to the function — no one outside can access it! 🌸 3️⃣ Block Scope (ES6 Magic 🌟) - With let and const, JavaScript introduced block-level scope — meaning variables exist only inside { } blocks. { let fruit = "Apple"; const color = "Red"; console.log(fruit, color); // ✅ Works } console.log(fruit); // ❌ ReferenceError 💬 var ignores block scope — but let and const respect it. 🧠 Quick Recap 🧭 Scope Summary: 🌍 Global Scope → Accessible everywhere | var, let, const 🌿 Function Scope → Accessible inside that function only | var, let, const 🌸 Block Scope → Accessible inside { } only | let, const 💛 Takeaway: - Scope controls visibility of variables 🕵️♀️ - Prefer let and const to avoid scope-related bugs - Understanding scope is the foundation for learning Closures (coming next 😉) 💬 Question for you: Which one confused you more when you started — global or block scope? Let’s discuss in the comments 👇 #javascript #frontenddevelopment #reactjs #webdevelopment #learninginpublic #womenintech #JSMadeEasy
To view or add a comment, sign in
-
🔍 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴? Hoisting is JavaScript’s default behavior of 𝗺𝗼𝘃𝗶𝗻𝗴 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 (𝗻𝗼𝘁 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻𝘀) 𝘁𝗼 𝘁𝗵𝗲 𝘁𝗼𝗽 𝗼𝗳 𝘁𝗵𝗲𝗶𝗿 𝘀𝗰𝗼𝗽𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝗰𝗼𝗱𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻. In simpler terms — during the compilation phase, JavaScript "scans" your code and allocates memory for variables and function declarations before executing it. That’s why you can use certain functions or variables before they’re defined in your code! 📘 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 console.log(myVar); // Output: undefined var myVar = 10; Behind the scenes, JavaScript treats this like: var myVar; // Declaration hoisted console.log(myVar); // undefined myVar = 10; // Initialization happens here ➡️ var is hoisted and initialized with undefined. However, if you use let or const, they’re hoisted too — but not initialized, leading to a ReferenceError if accessed before declaration. console.log(myLet); // ❌ ReferenceError let myLet = 20; ⚙️ 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 sayHello(); // ✅ Works! function sayHello() { console.log("Hello, World!"); } ➡️ Function declarations are hoisted completely (both the name and definition). But function expressions are not fully hoisted: sayHi(); // ❌ TypeError: sayHi is not a function var sayHi = function() { console.log("Hi!"); }; 💡 𝗪𝗵𝘆 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 𝟭. 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁: Helps you reason about how JS interprets and runs your code. 𝟮. 𝗔𝘃𝗼𝗶𝗱 𝗕𝘂𝗴𝘀: Prevents confusion around “undefined” or “ReferenceError”. 𝟯. 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲: Hoisting is a frequent JS interview question — understanding it deeply gives you an edge. 🧠 𝗧𝗼𝗽 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 #𝟮 Q: What is Hoisting in JavaScript, and how does it affect variable and function declarations? A: Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. var is hoisted and initialized with undefined. let and const are hoisted but not initialized (Temporal Dead Zone). Function declarations are fully hoisted, while function expressions are not. 🎯 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. JavaScript hoists declarations, not initializations. 2. var behaves differently from let and const. 3. Function declarations can be used before they’re defined — but function expressions cannot. #JavaScript #Hoisting #WebDevelopment #InterviewPreparation #TechTips #JavaScriptInterviewQuestions
To view or add a comment, sign in
-
'Question' Can JavaScript and Rust Really Be Compared? I’ve seen this question pop up often — and it’s a good one. At first glance, JavaScript and Rust seem worlds apart. But with the rise of WebAssembly (Wasm), that gap is shrinking fast. Let’s unpack this 👇 ⚙️ Different Roots, Different Strengths JavaScript was built for flexibility — it powers most of the web, both on the front and back end (thanks to Node.js). Rust was built for precision — it’s all about safety, performance, and control over memory. JS gives you speed of development. Rust gives you speed of execution. 🧩 How They Think About Memory JavaScript: Uses garbage collection. You don’t worry about memory — but sometimes pay for it in performance. Rust: Enforces memory safety at compile time. You manage ownership and lifetimes — and the compiler keeps you honest. It’s the difference between “it just works” and “it works, and I can prove it.” 🚀 Performance and Real Use Rust compiles to machine code. It’s as fast as C++, used in browsers, crypto, and embedded systems. JS is interpreted or JIT-compiled. It’s slower in computation-heavy tasks, but unbeatable for interactive web work. 🌐 Where They Shine Use Case JavaScript | Rust Front-end web ✅ | 🚫 (except via WebAssembly) Back-end APIs ✅ | ⚙️ (via Axum, Actix) Game engines / native apps ⚙️ | ✅ Embedded systems 🚫 | ✅ Performance-critical code 🚫 | ✅ Rapid prototyping ✅ | ⚙️ 🔗 Where They Meet: WebAssembly This is where things get exciting. Rust can compile to Wasm, and JavaScript can call that Rust code right inside the browser. That means: Rust handles the heavy computation (e.g., image processing, encryption). JavaScript handles the UI, interactivity, and web logic. A Tiny Example Here’s a simple example that calculates Fibonacci numbers in Rust — and runs in JS via WebAssembly. Rust (src/lib.rs): #[no_mangle] pub extern "C" fn fibonacci(n: u32) -> u32 { match n { 0 => 0, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } Compile it with: wasm-pack build --target web JavaScript: import init, { fibonacci } from "./pkg/your_wasm_package.js"; async function run() { await init(); console.log("Fibonacci(10) =", fibonacci(10)); } run(); And just like that — Rust is doing the math, JavaScript is showing the result. Final Thought Rust and JavaScript aren’t rivals — they’re complements. One gives you safety and speed; the other gives you reach and flexibility. Together, they’re redefining what’s possible in web and systems development.
To view or add a comment, sign in
-
🎬 “this” in JavaScript — The Most Confusing Character in the Movie! 🍿 If JavaScript was a Bollywood movie, this would be that mystery character who changes sides every 15 minutes 😅 Let’s decode the drama once and for all 👇 💡 What is this? this refers to the object that is currently calling the function. Simple? Wait for the twist 😏 “Main wahi karta hoon jo mera dil kehta hai…” (— Salman Khan, Wanted) And that’s exactly what this does — it behaves differently based on how it’s called! 🎭 1️⃣ Global Context console.log(this); 🧠 In browser → window In Node → {} “Main hi duniya hoon!” 🌍 🎭 2️⃣ Inside a Function function showThis() { console.log(this); } showThis(); In strict mode → undefined In non-strict mode → window “Kabhi main idhar, kabhi main udhar…” (— SRK energy 😅) 🎭 3️⃣ Inside an Object Method const hero = { name: "Hemant", sayName() { console.log(this.name); }, }; hero.sayName(); // Hemant Here, this points to the object that called it. “Jo mujhe call karega, main uska ho jaunga.” (— Classic Bollywood loyalty 💥) 🎭 4️⃣ Arrow Functions — The Plot Twist! const obj = { name: "Hemant", say: () => console.log(this.name), }; obj.say(); // undefined Arrow functions don’t have their own this. They inherit it from the parent scope — like family legacy 😂 “Main apne baap ka beta hoon!” (— Gangs of Wasseypur vibes 👊) 🎭 5️⃣ In Event Listeners button.addEventListener("click", function() { console.log(this); // points to the button }); When used in event listeners, this refers to the element that triggered the event. “Jo button dabayega, main uska ho jaunga!” 🎯 ⚙️ In Short: Contextthis Refers ToGlobalwindow / {}Function (non-strict)windowFunction (strict)undefinedObject MethodThat objectArrow FunctionParent scopeEvent ListenerThe element itself 💬 Pro Tip: If this confuses you — use arrow functions wisely or bind it explicitly 👇 const func = showThis.bind(hero); “Control ka button mere haath mein hai!” 😎 #JavaScript #WebDevelopment #CodingHumor #Frontend #LearningIsFun #Bollywood
To view or add a comment, sign in
-
-
⚙️✨ Mastering Hoisting in JavaScript — The Hidden Execution Magic! Ever wondered how JavaScript seems to “know” about your functions and variables even before they’re written in the code? 🤔 That secret superpower is called Hoisting 🚀 Let’s break it down in a way you’ll never forget 👇 💡 What is Hoisting? Hoisting is JavaScript’s default behavior of moving all declarations (variables and functions) to the top of their scope before the code executes. 👉 In simple words: You can use functions and variables before declaring them (but with rules!). 🧠 How It Works Before your code runs, JavaScript goes through two phases: 1️⃣ Creation Phase: It scans the code and allocates memory for variables and functions. Variables declared with var are set to undefined. let and const are placed in a Temporal Dead Zone (TDZ) until initialized. Function declarations are fully hoisted (you can call them before definition). 2️⃣ Execution Phase: Code runs line by line. Variables and functions are assigned actual values. 🧩 Example 1 – Variable Hoisting console.log(a); // undefined var a = 10; console.log(b); // ❌ ReferenceError let b = 20; ✅ var is hoisted and initialized as undefined. ❌ let is hoisted but not initialized — accessing it before declaration causes an error. ⚡ Example 2 – Function Hoisting greet(); // ✅ Works! function greet() { console.log("Hello, World!"); } sayHi(); // ❌ Error var sayHi = function() { console.log("Hi there!"); }; ✅ Function declarations are fully hoisted. ❌ Function expressions (including arrow functions) behave like variables — not hoisted with values. 🧩 Quick Explanation: Hoisting means the declaration is moved to the top of its scope (not the initialization). TDZ (Temporal Dead Zone) — the time between hoisting and actual declaration, where access causes an error. var gets hoisted and initialized with undefined. let and const get hoisted but stay uninitialized until the declaration line is executed. Functions declared using function keyword are fully hoisted (you can call them before they are defined). 🪄 Example 3 – The Complete Picture console.log(x); // undefined var x = 5; hello(); // ✅ Works function hello() { console.log("Hello JS!"); } sayHi(); // ❌ Error let sayHi = () => console.log("Hi JS!"); 💬 In Short: 🧩 Hoisting means declarations are processed first, execution happens later. 🚀 Functions are hoisted completely, variables only partially. ⚠️ let and const live in the Temporal Dead Zone until declared. 💭 Pro Tip: Understanding hoisting helps you avoid confusing bugs and makes you a more confident JavaScript developer 💪 💻 JavaScript reads your code twice — first to hoist, then to execute! Once you master this concept, debugging becomes much easier 😎 #JavaScript #WebDevelopment #ReactJS #Frontend #CodingTips #LearnCoding #Programming #DeveloperJourney
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree When I first heard about “Hoisting” in JavaScript, I thought it had something to do with lifting variables up 🏋️♀️😂 Turns out… I wasn’t entirely wrong! - Here’s a simple way to understand what Hoisting really means 👇 🧠 What is Hoisting? - When JavaScript runs your code, it does it in two phases: 1️⃣ 𝗠𝗲𝗺𝗼𝗿𝘆 𝗖𝗿𝗲𝗮𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it scans and “remembers” all variables and functions 2️⃣ 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it actually runs the code line by line - In the first phase, JS “hoists” (lifts) all variable and function declarations to the top of their scope. 💻 Example 1: Using var console.log(name); // undefined var name = "Virashree"; JS internally does this 👇 var name; // declaration hoisted console.log(name); // undefined name = "Virashree"; - So, name exists in memory but has no value yet — hence undefined. 🌿 Example 2: Using let and const console.log(age); // ❌ ReferenceError let age = 24; - Unlike var, let and const are hoisted too — but they stay in a special zone called the 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) until they’re declared. - That’s why accessing them before declaration throws an error instead of showing undefined. ⚙️ Function Hoisting — Two Types In JavaScript, there are two main ways to create functions: 1️⃣ Function Declaration 2️⃣ Function Expression - And they behave very differently when it comes to hoisting 👇 🌿 1. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 — Fully Hoisted ✅ The whole function is hoisted to the top of its scope. So you can call it before it’s defined. greet(); // ✅ Works fine function greet() { console.log("Hello, Virashree!"); } ➡️ Output: Hello, Virashree! Because JS hoists both the name and the body of the function. 🌸 2. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 — NOT Fully Hoisted When you assign a function to a variable (using var, let, or const), only the variable name is hoisted — not the function itself. sayHi(); // ❌ TypeError var sayHi = function() { console.log("Hi there!"); }; - If you used var, you’ll get: ❌ TypeError: sayHi is not a function - If you used let or const, you’ll get: ❌ ReferenceError: Cannot access 'sayHi' before initialization - So basically: 🚫 The variable gets hoisted, but the actual function definition does not. 🧩 Quick Recap var → Hoisted ✅ | Value: undefined let → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) const → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) function decl → ✅ Fully hoisted function expr → ⚠️ Partially hoisted (variable only) 🧠 Takeaway - So next time your code throws “is not a function,” - check how you declared it — not where! 😉 💬 Question for you: Which one confused you more — function declarations or function expressions? Comment below and I’ll break it down in my next #javascript #frontenddevelopment #webdevelopment #reactjs #learninginpublic #womenintech
To view or add a comment, sign in
-
In JavaScript, let arr = [] is not an array! This looks like an array, but it's not. At least, not in the way a C++ or Rust developer would define one. This distinction is crucial for understanding JS performance. 🖥️ The "Real" Array (Low-Level) In low-level languages, an array is a fixed-size, contiguous block of memory. If you declare [i32; 4] in Rust, you allocate exactly 128 bits (4 * 32-bit integers). - Pro: Extremely fast and memory-predictable. - Con: It's rigid. You can't just .append(). There's no guarantee the memory slot "next door" is free. 🧙♂️ The JavaScript "Array" (High-Level) A JS Array is actually a highly optimized, dynamic Object in disguise. The engine (like V8) is smart. It runs "optimizations" based on how you use the array. It generally picks between two internal structures: 1. The "Fast" Mode (Dynamic Array) - When: You use it sequentially (e.t., .push(), .pop()). - How: The engine allocates a contiguous block of memory with extra capacity (just like a Rust Vec or C++ std::vector). - The Catch: When that capacity runs out, the engine must allocate a new, larger block and copy all the old elements over. - This is why push() is usually O(1) (amortized), but sometimes O(n). 2. The "Slow" Mode (Hash Map) - When: You create a sparse array (e.g., arr[0] = 1; arr[1000] = 2;). - How: The engine sees this and gives up on the contiguous block. It's a waste of memory. - It switches the array's internal structure to a hash map (or dictionary). It only stores the key-value pairs that actually exist ('0': 1, '1000': 2). The Takeaway JavaScript trades the raw memory predictability of a C/Rust array for incredible developer flexibility. It's not a simple memory block; it's a sophisticated data structure managed by the engine, constantly adapting to your code. Knowing when it might be a fast array vs. a slow hash map is key to writing high-performance JS. #JavaScript #V8 #NodeJs #SoftwareArchitecture #Performance #DataStructures #JSEngine #TypeScript
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree 🧠 Understanding Execution Context & Call Stack in JavaScript When I started learning JavaScript, I used to wonder — 💭 “How does JS actually run my code line by line?” The answer lies in two magical words: ✨ Execution Context and 🧱 Call Stack Let’s make them super simple 👇 ⚙️ What is an Execution Context? Think of it as a container where your JS code runs. It decides: 🧩 Which variables and functions exist 📍 Where they live (scope) 🚀 How and in what order your code executes 🌍 1. Global Execution Context (GEC) This is created by default when your JS file starts running. It does 3 main things: 1️⃣ Creates a global object (window in browsers) 2️⃣ Sets up the this keyword 3️⃣ Allocates memory for variables & functions (this is where hoisting happens!) var name = "Virashree"; function greet() { console.log("Hello " + name); } greet(); ✅ First, JS creates memory for name and greet. ✅ Then, it executes line by line — calling greet(). 2. Function Execution Context (FEC) Every time you call a function, a new mini-world(Execution Context) is created just for that function! function greet() { var message = "Hello from function!"; console.log(message); } greet(); JS creates: - A new memory space for that function - Its own scope & variables - When done, it removes it from memory 🧱 The Call Stack — The Manager of All! - Imagine a stack of plates 🍽️ - The last plate you place on top is the first one you remove. - That’s exactly how the Call Stack works (LIFO rule — Last In, First Out) function one() { two(); } function two() { console.log("Inside two"); } one(); 🧩 JS Flow: 1️⃣ Global context created 2️⃣ one() pushed to stack 3️⃣ Inside it, two() pushed 4️⃣ two() finishes → removed 5️⃣ one() finishes → removed 6️⃣ Stack empty ✅ 💡 In short: - Every JS file starts with a Global Execution Context - Each function call creates a new context - The Call Stack manages them all in order 💬 Question for you: Have you ever seen that “Call Stack” section in browser DevTools? It’s this exact thing happening behind the scenes! ⚡ #javascript #frontenddevelopment #reactjs #webdevelopment #learninginpublic #womenintech #JSMadeEasy
To view or add a comment, sign in
-
This is the one of the simplest explanation of event loop in JavaScript. Imagine you are cooking rice and sauce for your family. You're the only one cooking and can do only one thing at a time. If you put the rice on the stove and just wait there until it boils before doing anything else, you’d waste a lot of time. Instead, what most of us do is put the rice on the cooker, then while it’s cooking, we start preparing the sauce or chopping vegetables. We don’t wait idly for one task to finish before starting another. JavaScript works similarly. It can only do one task at a time. This is called being single-threaded. The “rice cooking” in JavaScript could be something slow, like waiting for data from the a server or a timer. If JavaScript waited doing nothing until that slow task finishes, everything would freeze. JavaScript could have been horrible because it would be very slow. To avoid this, JavaScript uses helpers which are special tools that handle slow tasks in the background, like timers, network requests, or reading files. These helpers are called web APIs. When you put rice on the stove, the stove cooks it independently. When the rice is done, the stove signals you. In JavaScript, this signal is called a callback. The callback would inform you when the event is ready. Meanwhile, you keep working on other things until you finish your current task. After that, you check if the rice is ready. This checking is done by the event loop. In JavaScript: The call stack is like the list of tasks you’re actively working on. The callback queue is where the helpers put completed tasks waiting for you. The event loop constantly checks: “Is the call stack empty? If yes, take the next task from the callback queue and put it on the call stack.” This way, JavaScript never gets stuck waiting. It finishes tasks one by one but switches to new ready tasks as soon as it can. So, just like cooking multiple parts of a meal efficiently, JavaScript uses the event loop and helpers to manage tasks smoothly, making sure things don’t freeze and the app stays responsive. Congratulations for reading this far💯🙂
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
Like and Share #interview #javascript