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
JavaScript Variable Environments & Call Stack Explained
More Relevant Posts
-
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
-
🚀 Day 4 of #30DaysOfJavaScript (27 April 2026) Today I explored All Types of Functions in JavaScript (with definitions & examples) আজ আমি JavaScript-এর সব ধরনের Function শিখেছি (definition ও example সহ) 📌 Function (Definition | সংজ্ঞা) 👉 A function is a reusable block of code that performs a specific task. 👉 Function হলো reusable code block যেটা নির্দিষ্ট কাজ করে। 🔹 1. Function Declaration 👉 Defined using function keyword 👉 function keyword দিয়ে define করা হযfunction greet() { console.log("Hello"); } greet(); 🎯 Use: General reusable logic 🔸 2. Function Expression 👉 Function stored in a variable 👉 variable এর ভিতরে function রাখা হয়const greet = function() { console.log("Hi"); }; 🎯 Use: Dynamic function usage, callbacks ⚡ 3. Arrow Function (ES6) 👉 Short syntax using => 👉 shortcut way te function লেখা হয়const add = (a, b) => a + b; 🎯 Use: Clean & short code (React e beshi use) 🔁 4. Callback Function 👉 Function passed as argument to another function 👉 ekta function ke onno function er moddhe pathano hoy function greet(name, callback) { console.log("Hi " + name); callback(); } greet("Fahmida", () => console.log("Done")); 🎯 Use: Async কাজ, event handling 🧠 5. Anonymous Function 👉 Function without a name 👉 function er kono naam thake na setTimeout(function() { console.log("Hello"); }, 1000); 🎯 Use: One-time use, callbacks 🔄 6. IIFE (Immediately Invoked Function) 👉 Runs immediately after definition 👉 define korar sathe sathe run hoy (function() { console.log("Run instantly"); })(); 🎯 Use: Private scope, global variable avoid 🧩 7. Higher-Order Function 👉 Function that takes/returns another function 👉 function jeta onno function ke receive ba return kore function multiplier(x) { return function(y) { return x * y; }; } 🎯 Use: map, filter, reusable logic 🧱 8. Constructor Function 👉 Used to create objects with new 👉 object create korar jonno use hoy function User(name) { this.name = name; } const u1 = new User("Fahmida"); 🎯 Use: Object creation (OOP style) ⚠️ Common Mistakes 👉 Arrow function e this confusion 👉 Forgetting return 👉 Overusing anonymous functions 🔥 Learning 👉 Functions are the heart of JavaScript — everything from React components to APIs depends on them 👉 JavaScript-এর সবচেয়ে powerful concept হলো function #JavaScript #FullStackDeveloper #LearningInPublic #WebDevelopment #30DaysChallenge ়
To view or add a comment, sign in
-
Today I froze my Chrome tab with one line of JavaScript. console.time(); /(a+)*b$/.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaba"); console.timeEnd(); // 24,000 ms This is catastrophic backtracking — a well-known but still underappreciated problem in regex engines. The pattern (a+)*b$ looks innocent, but V8's regex engine (Irregexp) is backtracking-based: it tries 2^n ways to partition the a's between the inner + and the outer * before concluding there's no match. 28 a's = ~268 million paths to explore. For a regex. What surprised me is that V8 already ships a fix — a non-backtracking linear-time regex engine, available since V8 v8.8 (2021). You can enable it in Node.js: node --enable-experimental-regexp-engine-on-excessive-backtracks test.js It falls back to the linear engine after 50K backtracks. The same pattern completes instantly. So why isn't this on by default? → The linear engine doesn't support backreferences, lookahead, or lookbehind → Irregexp is orders of magnitude faster on patterns that don't blow up → It's experimental and not part of the ECMAScript spec The TC39 proposal that would address this at the language level — atomic groups and possessive quantifiers (?>...) — has been sitting at Stage 1 since October 2021. Meanwhile, ReDoS (Regular Expression Denial of Service) remains a real attack vector. If your Node.js server accepts user-provided regex patterns, or even if a developer writes an unfortunate validation pattern, one request can block your entire event loop. Practical takeaways: • Avoid nested quantifiers: (a+)*, (a*)+ , (a+)+ are all dangerous • Use the re2 npm package server-side when running untrusted patterns • Consider the --enable-experimental-regexp-engine-on-excessive-backtracks flag for Node.js services • JS doesn't support atomic groups or possessive quantifiers — you can't opt out of backtracking at the pattern level A DFA-based engine would handle this in O(n) — one pass, no branching. The irony is that patterns most dangerous for backtracking engines often describe the simplest possible languages. #javascript #nodejs #regex #webdev #security
To view or add a comment, sign in
-
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
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
-
🔑 JavaScript Maps – Quick Guide 1. What is a Map? A collection of key‑value pairs (like a dictionary). Keys can be any type (string, number, object, etc). Preserves insertion order. Optimized for frequent additions/removals. Iterable → can use for...of and forEach() directly. 2. Creating Maps // Empty Map + set() const fruits = new Map(); fruits.set("apples", 500); fruits.set("bananas", 300); // From array const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); 3. Core Methods MethodPurposeExampleReturns set(key, value)Add/change valuefruits.set("mangos", 100)Updated Map get(key)Retrieve valuefruits.get("apples")500 delete(key)Remove entryfruits.delete("bananas")Boolean has(key)Check existencefruits.has("oranges")true/false clear()Remove all entriesfruits.clear()Empty Map sizeCount entriesfruits.sizeNumber 4. Iteration // for...of for (const [key, value] of fruits) { console.log(key, value); } // forEach fruits.forEach((value, key) => { console.log(key, value); }); 5. Map vs Object FeatureObjectMap IterationNot directly iterable✅ Directly iterable SizeNo size property✅ .size Key typesStrings/Symbols only✅ Any datatype OrderNot guaranteed✅ Insertion order preserved Default keysPrototype keys exist✅ No default keys 6. Type & Identity typeof fruits; // "object" fruits instanceof Map; // true 📝 Exercise Answer Which method can be used to add elements to a Map? 👉 Correct answer: set() 🎯 Memory Hook Think of a Map as a super‑powered Object: Any type of key. Ordered. Easy to count with .size. Perfect for dictionaries, caches, and lookups.
To view or add a comment, sign in
-
Day 1/100 of Javascript Today Topic : Javascript Engine JS code is first tokenized and parsed into an AST (Abstract Syntax Tree). The interpreter converts this into bytecode and begins execution. While running, the engine identifies hot code and uses a JIT compiler to optimize it into machine code for better performance. 1. What is Tokenizing? Tokenizing = breaking your code into small meaningful pieces (tokens) After tokenizing: Code Part Token Type let keyword x identifier = operator 10 literal ; punctuation 2. What Happens After Tokenizing? Tokens → Parsing Parser converts tokens into: 👉 AST (Abstract Syntax Tree) Example (conceptually): VariableDeclaration ├── Identifier: x └── Literal: 10 3. Why JavaScript is JIT Compiled? JS is called JIT (Just-In-Time) compiled because: 👉 It compiles code during execution, not before. ⚙️ Flow Code → Tokens → AST → Bytecode → Execution → Optimization → Machine Code 🔥 Step-by-Step 1. Interpreter Phase AST → Bytecode Starts execution immediately 👉 Fast start, but not the fastest execution 2. Profiling Engine watches: Which code runs frequently (hot code) 3. JIT Compilation Hot code → compiled into optimized machine code 👉 Now it runs much faster Also looked at different JavaScript engines: 👉V8 (Google) → Uses Ignition (interpreter) + TurboFan (optimizer), heavily optimized for performance 👉SpiderMonkey (Mozilla) → Uses Interpreter + Baseline + IonMonkey (JIT tiers) 👉Chakra (Microsoft) → Has its own JIT pipeline with profiling and optimization stages Each engine has a different internal architecture, but all follow the same core idea. Reference : 1. https://lnkd.in/gvCjZRJK 2. https://lnkd.in/gwcWp-dE 3. https://lnkd.in/gWGiNJZk. 4. https://lnkd.in/g7D4MiQ8 #Day1 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
This is the cleanest: "Go do other stuff if you have any - come back here to continue after delayMS milliseconds" pattern in JS; AKA: "Sleep" (note, NOT the same as just: "do this later in delayMS ms", see info at the end. Let's analyze, because this single line actually leads to a **7 steps process**: 1. A new unsettled Promise instance is created - saved in V8's heap memory. 2. The executor function of the Promise - runs immediately: calls the setTimeout API - this sets up a timer (with some help from the OS) in the browser host environment (which, in the context of Google Chrome, is the engine process known as Blink), to wake-up after delayMS. 3. The "await" mechanism kicks in. This is a Javascript/V8 thing - it suspends execution on that spot, creates a "continuation" mechanism that is meant to run as soon as the Promise is resolved. A kind of syntactic equivalent to "promise.then(continuation)" - with some nuances (see my other post about await for more info about this). 4. Now, if there are outer execution contexts - they run - until the JS call stack is empty. Control is yielded back to Blink. DelayMS has passed? Timer triggers a "wake-up" call - puts the timer task on the macrotask queue, to (probably, assuming no other higher priority async macrotasks) be executed. Blink executes the JS callback in V8. 5. That callback is simply "resolve" - the specific resolve for the specific Promise instance we created in step 1. 6. Resolving the promise triggers the "continuation" mechanism - which essentially wraps any code after "await" to be run as a Microtask and schedules it in the Microtasks queue (an async queue that lives inside V8). 6. If there is synchronous code on the call stack - it will run. 7. A microtasks checkpoint runs each time after JS script runs and the call stack is empty: the continuation microtask will run. When would you use it? For example when you need to: "do some work -> wait a bit -> do some work again", e.g. a "retry mechanism". You might ask, why not just use: setInterval(()=> doWork(), delayMS)...? That's a different thing. The setInterval thing is: tick: do work. tick: do work. ... The first thing is: do work, wait (maybe do other stuff). do work, wait (maybe do other stuff). ... #javascript #promise #sleep
To view or add a comment, sign in
-
-
🚀 Day 24 – Functions & Advanced Concepts in JavaScript Today’s focus is not just theory — it’s how these concepts are used in REAL applications 👇 🔹 1. Debounce 👉 Executes function only after user stops triggering it for a delay. function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Real-time scenario: In an e-commerce website, when a user searches for a product, we don’t call API on every keystroke. Instead, we wait until the user stops typing → then trigger API. 👉 Prevents 20+ unnecessary API calls! 🔹 2. Throttle 👉 Ensures function runs only once in a given interval. function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; flag = false; fn.apply(this, args); setTimeout(() => { flag = true; }, limit); }; } Real-time scenario: While scrolling Instagram/LinkedIn feed, scroll events fire continuously. Throttle ensures smooth performance by limiting executions. 👉 Prevents UI lag & improves performance 🔹 3. Currying 👉 Converts multiple arguments into nested functions. function curry(a) { return function (b) { return function (c) { return a + b + c; }; }; } console.log(curry(2)(3)(4)); // 9 Real-time scenario: In large apps, we create reusable utility functions. Example: Tax calculator → instead of passing all values every time, we reuse partial functions. 👉 Helps in clean & reusable code 🔹 4. Memoization 👉 Caches results to avoid recalculating. function memoize(fn) { const cache = {}; return function (n) { if (cache[n]) return cache[n]; const result = fn(n); cache[n] = result; return result; }; } Real-time scenario: In dashboards (finance/analytics apps), heavy calculations run repeatedly. Memoization stores results → avoids recomputation. 🔹 5. Closures ⭐ 👉 A function remembers variables from its outer scope even after execution. function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Real-time scenario: ✔ Data hiding ✔ Maintaining state (like counters, caches) Used in: ✔ Counters (cart items count) ✔ Private variables (data hiding) ✔ setTimeout inside loops 👉 Helps maintain state without global variables 🔹 6. Pure Functions 👉 Function that always returns same output for same input and has no side effects. function add(a, b) { return a + b; } Real-time scenario: In state management (Angular/React), pure functions ensure predictable updates. Why important? ✔ Predictable ✔ Easy to test ✔ Used in frameworks like Angular & React 👉 Easier debugging & testing #JavaScript #FrontendDeveloper #Angular #InterviewPrep #Coding #WebDevelopment
To view or add a comment, sign in
-
🔑 JavaScript Set Reference – Quick Guide 1. Creation js const mySet = new Set(); // empty const letters = new Set(["a","b","c"]); // from array 2. Core Methods MethodPurposeExampleReturnsadd(value)Add elementmySet.add("x")Updated Setdelete(value)Remove elementmySet.delete("a")Booleanclear()Remove all elementsmySet.clear()Empty Sethas(value)Check existencemySet.has("b")true/falsesizeCount elementsmySet.sizeNumber 3. Iteration Methods MethodPurposeExampleforEach(callback)Run function for each valuemySet.forEach(v => console.log(v))values()Iterator of valuesfor (const v of mySet.values()) {}keys()Same as values()mySet.keys()entries()Iterator of [value, value] pairsmySet.entries() 4. Set Logic Methods (ES2025+) MethodPurposeunion(otherSet)Combine elements of both setsintersection(otherSet)Common elementsdifference(otherSet)Elements in one set but not the othersymmetricDifference(otherSet)Elements in either set but not bothisSubsetOf(otherSet)True if all elements are in other setisSupersetOf(otherSet)True if contains all elements of other setisDisjointFrom(otherSet)True if no common elements 5. Example Usage js const a = new Set([1,2,3]); const b = new Set([3,4,5]); console.log(a.union(b)); // {1,2,3,4,5} console.log(a.intersection(b)); // {3} console.log(a.difference(b)); // {1,2} console.log(a.symmetricDifference(b));// {1,2,4,5} 6. Key Notes Unique values only → duplicates ignored. Insertion order preserved. Sets are iterable (unlike WeakSets). Useful for mathematical set operations and fast membership checks. 🎯 Memory Hook Think of a Set as a mathematical set in code: No duplicates. Easy union/intersection/difference. Fast membership checks with .has().
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