💛 JavaScript Functions (Part 2) — Types of Functions Explained Clearly 🔥 In JavaScript, functions are not all the same. How you define a function changes: ▪️hoisting behavior ▪️readability ▪️this binding ▪️how it’s used in real projects Let’s explore the most important types 👇 ♦️ Function Statement (Function Declaration) function greet() { console.log("Hello!"); } ✅ Key Points ▪️Fully hoisted ▪️Can be called before definition ▪️Stored completely during memory creation phase greet(); // works 💡 Best for general-purpose logic ♦️ Function Expression A function assigned to a variable. var add = function (a, b) { return a + b; }; ⚠️ Important ▪️Variable is hoisted as undefined ▪️Function is not hoisted add(); // ❌ TypeError 💡 Useful when functions behave like values ♦️ Anonymous Function A function without a name. setTimeout(function () { console.log("Hello"); }, 1000); 🧠 Key Idea ▪️Used where a function is needed temporarily ▪️Cannot exist on its own ▪️Mostly used as callbacks ♦️ Named Function Expression (NFE) A function expression with a name. const factorial = function fact(n) { if (n === 0) return 1; return n * fact(n - 1); }; ✅ Benefits ▪️Name is available inside the function only ▪️Helpful for recursion ▪️Better debugging (stack traces) fact(5); // ❌ not accessible outside ♦️ Arrow Functions 🏹 Introduced in ES6 for cleaner syntax. const multiply = (a, b) => a * b; 🔹 Differences from Normal Functions ▪️No own this ▪️No arguments object ▪️Lexically binds this Cannot be used as constructors const obj = { x: 10, show: () => console.log(this.x) }; obj.show(); // undefined ♦️ First-Class Functions 🥇 JavaScript treats functions as values. This means functions can: ✔️ Be assigned to variables ✔️ Be passed as arguments ✔️ Be returned from other functions 🔹 Example function greet() { return function () { console.log("Hello!"); }; } const sayHello = greet(); sayHello(); 👉 This is the foundation of: Callbacks, Closures and Higher-Order Functions 💡 Why This Matters Understanding function types helps you: ✅ Avoid hoisting bugs ✅ Use correct syntax in interviews ✅ Write cleaner, modern JS ✅ Understand React & async patterns 📌 This was Part 2 Next up 🔥 👉 Part 3: Higher-Order Functions, Callback Functions, IFFE & Real-World Use Cases If this helped you, drop a 💛 or share 🔁 #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
JavaScript Function Types Explained: Declarations, Expressions, and More
More Relevant Posts
-
💛 JavaScript Functions (Part 3) — HOFs, Callbacks & Real-World Magic 🚀 If you truly understand this post, you’ll understand: ▪️async JavaScript ▪️event handling ▪️closures in real life ▪️memory leaks (and how to avoid them) Let’s dive in 👇 ♦️ Higher-Order Functions (HOF) A Higher-Order Function is a function that: 👉 Takes another function as an argument OR returns a function function calculate(operation, a, b) { return operation(a, b); } function add(x, y) { return x + y; } calculate(add, 2, 3); // 5 ✔️ calculate is a HOF ✔️ add is a callback ♦️ Callback Functions A callback function is: 👉 A function passed as an argument into another function to be executed later setTimeout(function () { console.log("Executed later"); }, 1000); ✔️ JavaScript is async because of callbacks ✔️ Foundation of promises & async/await ♦️ Built-in HOFs You Already Use const nums = [1, 2, 3, 4]; nums.map(n => n * 2); nums.filter(n => n > 2); nums.reduce((a, b) => a + b, 0); 👉 map, filter, reduce are classic HOFs ♦️ Event Listener — Callback in Action 🎯 button.addEventListener("click", function () { console.log("Button clicked"); }); ✔️ addEventListener is a HOF ✔️ Callback runs only when event occurs ♦️ Closure with Event Listener 🧠 function attachCounter() { let count = 0; button.addEventListener("click", function () { count++; console.log(count); }); } attachCounter(); 🤯 Even after attachCounter() finishes: ▪️count is remembered ▪️Closure keeps lexical environment alive ♦️ Garbage Collector & Closures ♻️ JavaScript automatically frees memory using a Garbage Collector. 👉 Memory is cleaned only when no references exist. ⚠️ Problem: function attachListener() { let heavyData = new Array(1000000); button.addEventListener("click", function () { console.log(heavyData.length); }); } ❌ heavyData stays in memory ❌ Closure keeps reference alive ♦️ Solution — removeEventListener 🧹 function attachListener() { let count = 0; function clickHandler() { count++; console.log(count); } button.addEventListener("click", clickHandler); // later button.removeEventListener("click", clickHandler); } ✔️ Memory is released ✔️ Closure is removed ✔️ Garbage Collector can clean up 🧠 Key Takeaways ▪️HOFs power modern JavaScript ▪️Callbacks enable async behavior ▪️Event listeners rely on closures ▪️Unremoved listeners can cause memory leaks ▪️removeEventListener is critical for performance 💡 Why This Matters Understanding this helps you: ✅ Write efficient event-driven apps ✅ Avoid memory leaks ✅ Understand React hooks & DOM handling ✅ Answer tricky interview questions 📌 This completes the Functions saga 🎉 Next topic will certainly be🔥 👉 Event Loop, Microtask Queue & Callback Queue (Deep Dive) If this helped you, drop a 💛 or share 🔁 #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
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
-
-
Most of us treat JSON.parse() as a simple utility, but internally it’s one of the most memory-sensitive operations in JavaScript. Here’s what actually happens, step by step 👇 When JSON.parse() is called, the browser engine (like V8) first scans the raw JSON string and identifies structural characters such as {, [, ", : and ,. This scanning step is highly optimized and often SIMD-accelerated, meaning multiple characters are processed in a single CPU instruction. After scanning, the parser walks through the string in a single pass using a recursive descent approach: • When it sees {, it creates a JavaScript object • When it sees [, it creates an array • Keys and values are attached step by step This is how the full JavaScript object tree is built in memory. Now comes the critical part: memory usage. Think of the process like this: 1️⃣ JSON arrives [ Raw JSON String ] The response is stored in memory as plain text. 2️⃣ Parsing starts [ Raw JSON String ] [ Parser State + Temporary Buffers ] The engine scans and tokenizes the string. 3️⃣ Object creation begins [ Raw JSON String ] [ JS Object Tree (partially built) ] [ Temporary Native Memory (Zones) ] Objects and arrays are created recursively. 4️⃣ Peak memory moment (danger zone) [ Raw JSON String ] [ Full JS Object Tree ] [ Temporary Parser Memory ] At this point, peak memory usage can be 2x–4x the size of the JSON. This short-lived but sharp jump is called a memory spike. JavaScript objects are heavy. Pointers, metadata, hidden class references, and value representations mean parsed JSON often consumes 6–10x more memory than the raw string. 5️⃣ Parsing finishes [ JS Object Tree ] Only now does the original string become eligible for Garbage Collection. Why didn’t GC help earlier? Because during parsing, everything is still strongly referenced. The string is being read, the object tree is still being built, and temporary memory is active. From the GC’s point of view, nothing is “dead”, so nothing can be freed. If this memory spike crosses the browser’s per-process heap limit, the result is familiar: • UI freezes • “JavaScript heap out of memory” • Browser tab crashes (“Aw, Snap!”) This is not a memory leak. It’s a temporary spike that grows faster than GC can react. Key takeaway: JSON.parse() is CPU-fast, but memory-expensive. For large payloads, loading everything and parsing at once is risky. Streaming parsers that process data chunk by chunk are far safer and more scalable. Understanding this changed how I handle large APIs on both the frontend and in Node.js. #JavaScript #BrowserInternals #MemoryManagement #WebPerformance #FrontendEngineering #NodeJS
To view or add a comment, sign in
-
-
🌟 10 Useful JavaScript Snippets You Might Not Know Quick, practical JS helpers that can save time and clean up your code! 💡 --- 1️⃣ Randomize an array (Fisher-Yates shuffle) ```javascript const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5); console.log(shuffleArray([1, 2, 3, 4, 5])); ``` 2️⃣ Flatten nested arrays ```javascript const flatten = (arr) => [].concat(...arr); console.log(flatten([1, [2, 3], [4, [5]]])); ``` 3️⃣ Check if an object is empty ```javascript const isEmpty = (obj) => Object.keys(obj).length === 0; console.log(isEmpty({})); // true ``` 4️⃣ Remove duplicates from an array ```javascript const unique = (arr) => [...new Set(arr)]; console.log(unique([1, 2, 2, 3, 3, 4])); ``` 5️⃣ Get current date in YYYY-MM-DD format ```javascript const today = () => new Date().toISOString().slice(0, 10); console.log(today()); ``` 6️⃣ Capitalize the first letter of a string ```javascript const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize("hello world")); ``` 7️⃣ Convert RGB to Hex ```javascript const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); console.log(rgbToHex(255, 100, 50)); ``` 8️⃣ Wait/delay function ```javascript const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); await delay(2000); // waits 2 seconds ``` 9️⃣ Copy text to clipboard ```javascript const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello, devs! 👨💻"); ``` 🔟 Extract parameters from URL ```javascript const getParams = (url) => Object.fromEntries(new URL(url).searchParams); console.log(getParams('https://lnkd.in/g3Y-T5jw')); ``` --- 📌 Which snippet did you find most useful? Have a better version? Share below! 👇 --- 📌 Follow Sasikumar S for more hands-on developer content ❤️ Join skAI – Daily Developer Learning Community for daily tips, growth hacks & career opportunities 💌 Repost to help others in your network 🤝 Connect: sasiias2024@gmail.com 💟 Explore more: sk-techland.web.app #JavaScript #WebDevelopment #CodingTips #JS #DeveloperTools #Programming #CodeSnippets #TechTips #Frontend #LearnToCode
To view or add a comment, sign in
-
💛 JavaScript Event Loop — How Async JavaScript REALLY Works 🚀 JavaScript looks asynchronous… but under the hood, it is single-threaded 😮 So how does JS handle: ▪️setTimeout▪️Promises▪️Fetch APIs▪️Event listeners The answer is the Event Loop. Let’s break it down step-by-step 👇 ♦️ Call Stack 📚 The Call Stack is where JavaScript executes code. ▪️Uses LIFO (Last In, First Out) ▪️Executes one function at a time ▪️If the stack is busy → JS can’t do anything else function a() { b(); } function b() { console.log("Hello"); } a(); Call Stack flow: Global → a() → b() → pop → pop ♦️ Web APIs 🌐 (Browser Power) Web APIs are not part of JavaScript. Browsers provide:▪️setTimeout▪️fetch▪️DOM events▪️console▪️localStorage setTimeout(() => { console.log("Hi"); }, 1000); 👉 Timer is handled by Web APIs, not Call Stack. ♦️ Callback Queue (Task Queue) ⏳ When a Web API finishes its task: 👉 Its callback is pushed into the Callback Queue Examples:▪️setTimeout▪️setInterval▪️DOM events ♦️ Microtask Queue ⚡ The Microtask Queue has higher priority than Callback Queue. Contains: ▪️Promise callbacks (.then, .catch, .finally)▪️MutationObserver ▪️queueMicrotask ♦️ Event Loop 🔁 (The Orchestrator) The Event Loop constantly checks: 1️⃣ Is Call Stack empty? 2️⃣ If yes → execute all Microtasks 3️⃣ Then → take one task from Callback Queue 4️⃣ Repeat forever 👉 Microtasks always run before callback queue tasks ♦️ Execution Order Example 🔥 console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 🖨️ Output: Start End Promise Timeout Why? ▪️Promise → Microtask Queue▪️setTimeout → Callback Queue ▪️Microtasks run first ♦️ Starvation of Callback Queue ⚠️ Starvation happens when: 👉 Callback Queue tasks never get executed because Microtask Queue never becomes empty. 🔹 Starvation Example function endlessMicrotasks() { Promise.resolve().then(endlessMicrotasks); } endlessMicrotasks(); setTimeout(() => { console.log("Timeout"); }, 0); ❌ setTimeout never runs ❌ Callback Queue is starved ❌ Microtasks keep blocking it ♦️ Why JavaScript Allows This ▪️Promises are designed for critical async logic ▪️Microtasks must finish before rendering & callbacks ▪️Misuse can freeze apps 🧠 Visual Flow (Mental Model) Call Stack ↓ Web APIs ↓ Microtask Queue (High Priority) ↓ Callback Queue (Low Priority) ↓ Event Loop 🧠 Interview One-Liner 🥇 The Event Loop is a mechanism that allows the single-threaded JavaScript engine to handle asynchronous operations efficiently without blocking the main execution thread. Event Loop Deep Dive 👇 🔗https://lnkd.in/gWyaTyFR If this helped you, drop a 💛 or share 🔁 Next topic 👉 Js Engine | Google's V8 Engine (Deep Dive) 🔥 #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
To view or add a comment, sign in
-
-
🧠 Memory Leaks in JavaScript — a production issue I caused myself A while ago, I was debugging a frontend issue where: ✅ The UI worked correctly ✅ There were no errors ❌ The application became slower over time After digging deeper, I realized the problem wasn’t the API or React re-renders. I hadn’t cleaned up properly. Event listeners and timers were still alive even after components were gone. That’s when I went down the rabbit hole of JavaScript memory leaks. Here are the key patterns I learned (and now actively watch for): 🔴 1. Accidental Global Variables A small mistake that can silently leak memory. function createLeak() { leakedData = new Array(10000).fill("*"); // becomes global ❌ } Correct fix: "use strict"; function createLeak() { const data = new Array(10000).fill("*"); // properly scoped ✅ } 🔴 2. Event Listeners Without Cleanup (my main issue) Removing a DOM element does not remove its event listeners. button.addEventListener("click", () => { console.log("clicked"); }); // button removed, listener still retained ❌ Correct fix: function handleClick() { console.log("clicked"); } button.addEventListener("click", handleClick); // cleanup button.removeEventListener("click", handleClick); 🔴 3. Closures Holding Unnecessary Data Closures keep references alive longer than expected. function createHandler() { const largeData = new Array(10000).fill(1); return () => console.log(largeData.length); } const handler = createHandler(); // largeData stays in memory ❌ Better approach: Avoid capturing large or long-lived data inside closures unless required. 🔴 4. Timers That Never Stop Timers are another common source of leaks when not cleaned up. setInterval(() => { console.log("running..."); }, 1000); Correct fix: const id = setInterval(() => { console.log("running..."); }, 1000); clearInterval(id); 🧪 What this experience taught me Garbage collection isn’t a safety net for poor cleanup Memory leaks rarely fail fast — they degrade performance over time Long-running SPAs are especially vulnerable Since then, I make it a habit to: ✅ Clean up event listeners and timers ✅ Review closures carefully ✅ Treat useEffect cleanup as mandatory, not optional 🚀 Final thought Most memory leaks don’t break applications — they quietly erode performance. And very often, the root cause isn’t complex logic — it’s missing cleanup. 💬 Curious: Have you ever debugged a memory leak in production? What turned out to be the root cause? #JavaScript #FrontendEngineering #WebPerformance #React #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
🧠 JavaScript – Operators & Conditional Statements Making Decisions Using Code In real applications, programs don’t just run line by line they think, compare, and decide what to do next. This is where operators and conditional statements become essential. 🔹 Operators in JavaScript Operators are used to perform actions on values. ➕ Arithmetic Operators Used for calculations. let a = 10; let b = 5; a + b; // 15 a - b; // 5 a * b; // 50 a / b; // 2 a % b; // 0 Used in: Calculations Scores Prices Counters 🔍 Comparison Operators Used to compare values. 10 == "10"; // true 10 === "10"; // false 10 > 5; // true == → compares value === → compares value and type (recommended) 👉 Always prefer === in modern JavaScript. 🔗 Logical Operators Used to combine conditions. true && false; // false true || false; // true !true; // false Used for: Login checks Multiple conditions Access control 🔹 Conditional Statements Conditional statements help JavaScript choose different paths based on conditions. ✅ if – else let age = 20; if (age >= 18) { console.log("Eligible to vote"); } else { console.log("Not eligible"); } Used for: Validations Permissions User actions 🔁 else if (Multiple Conditions) let marks = 75; if (marks >= 90) { console.log("Excellent"); } else if (marks >= 60) { console.log("Good"); } else { console.log("Needs improvement"); } 🔀 switch Statement Best when checking one value against many cases. let role = "admin"; switch (role) { case "admin": console.log("Full access"); break; case "user": console.log("Limited access"); break; default: console.log("Guest access"); } Used in: Menu options User roles Status handling 🧠 Simple Way to Think Operators → compare values Conditions → make decisions Code → behaves differently based on input This is how JavaScript becomes smart. ✅ Key Takeaway If you understand: ✔ Operators ✔ if–else logic ✔ switch cases You can control how your program behaves — a core skill in web development. . . #JavaScript #WebDevelopment #ProgrammingBasics #LearningInPublic #FrontendDevelopment #FullStackJourney
To view or add a comment, sign in
-
-
I had one of those moments where a simple piece of JavaScript made me stop and think about how much the language is doing behind the scenes. I was reviewing some JavaScript fundamentals recently and ended up thinking about how the language actually prepares and executes our code. A simple recursive function started the whole reflection: function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); } console.log(factorial(3)); // Output: 6 At first glance, it looks like JavaScript is calling the function before the function body is fully defined. That is not what is happening. JavaScript always parses the entire file first. It checks that every brace is matched, builds the execution context, and hoists function declarations with their complete bodies. Only after this preparation step does it begin executing the code line by line. This is why recursion works so smoothly. The engine already knows that factorial is a complete function before it ever reaches the first call. While thinking about this, I compared it to closures and variable hoisting. Closures work because JavaScript remembers the surrounding lexical environment even after the outer function has finished running. For example: function outer() { let count = 0; return function inner() { count++; return count; }; } const fn = outer(); fn(); // Output: 1 fn(); // Output: 2 Even though outer has returned, the inner function still has access to count. JavaScript preserved that environment during the initial parsing phase. One important detail that often gets overlooked is naming. JavaScript is case sensitive and requires unique identifiers within the same scope. If the outer function and inner function accidentally share the same name, or if a variable shadows a function name, the engine will throw an error during parsing. The preparation phase catches these conflicts before any code runs. This reinforces how strict JavaScript is about scope and naming rules, especially when closures are involved. Hoisting shows a similar pattern. Function declarations are lifted with their full definitions, while variables behave differently: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; JavaScript already knows that a and b exist, but only var is initialized early. let and const stay uninitialized until execution reaches their line. All of this ties back to how JavaScript prepares the program before running it. The engine builds a complete mental map of functions, scopes, variables, and names before executing anything. What looks like simple line‑by‑line execution is actually the second phase of a much deeper process. The first phase is where the engine resolves scopes, hoists declarations, checks for naming conflicts, and sets up the environment that makes recursion, closures, and hoisting behave the way they do. Understanding how JavaScript works inside matters as much as syntax. Has simple code ever changed how you see it?
To view or add a comment, sign in
-
JavaScript bugs rarely come from bad syntax. They come from misunderstanding what a variable actually holds. Once memory clicks, behavior stops feeling random. 👉 Pass by value vs pass by reference isn’t theory. 👉 It’s runtime behavior and most hard bugs come from getting it wrong. Here’s the mental model that changed how I reason about code. 🧠 What variables actually store In JavaScript, variables don’t all store data the same way. • Primitives (number, string, boolean, null, undefined) → store the actual value • Objects, arrays, classes → store a memory address That single distinction explains: • shared state bugs • broken equality checks • “random” side effects • functions mutating things they shouldn’t ⚡ Why primitives feel predictable let a = 10; let b = a; b++; Two variables. Two independent values. That’s why primitives: • are passed by value • stay isolated across function calls • don’t leak changes across scopes Safe. Local. Predictable. 🌐 Why reference types behave differently let a = []; let b = a; b.push(1); You didn’t update b. You updated the memory both point to. Because: • assignment copies the address, not the data • multiple variables can point to the same location • mutation affects every shared reference This is where subtle bugs are born. ❌ Equality checks that look wrong (but aren’t) [] === [] // false Not because JavaScript is weird, but because it compares addresses, not structure. Two identical-looking objects: • separate allocations • different addresses • not equal Miss this, and conditionals silently fail. This is also a common interview discussion point. 🧨 Mutation vs reassignment (the real distinction) Same syntax. Very different mechanics. • Mutation (push, property update) → changes data at the address → affects all references • Reassignment (= new object) → creates a new address → breaks the link Understanding this explains: • why functions mutate external state • why “local changes” aren’t always local ⚠️ Why const still allows mutation const arr = []; arr.push(1); Valid because: • the reference didn’t change • only the data inside it did const locks the address not, the contents. This alone removes confusion around: • immutability • state updates • “why this still changed” 🎯 Why this actually matters If you don’t understand reference vs value: • you can’t reason about state • you can’t trust function boundaries • you’ll ship bugs that are hard to reproduce • debugging feels like chasing ghosts Once you do understand it, you start to: • predict side effects instead of reacting to them • design safer APIs • write code that scales mentally, not just technically For me, this was the shift from writing code to reasoning about runtime behavior. If you enjoy thinking about how systems actually behave not just how code looks let’s connect 🤝 #JavaScript #SoftwareEngineering #ProgrammingConcepts #SystemThinking #Debugging #DeveloperMindset
To view or add a comment, sign in
-
🚀 JavaScript Internals | Event Loop, JS Engine & Sync vs Async (With Practical Examples) 📘 JavaScript Deep Dive – From Basics to Production-Level Understanding Today, I revised how JavaScript actually executes code under the hood, focusing on the JavaScript Engine, Event Loop, libuv, and the real difference between synchronous and asynchronous execution, using practical examples. 🔹 JavaScript Engine (How code runs) The JavaScript Engine (like V8) executes code using: Call Stack → executes functions in LIFO order Memory Heap → stores objects and variables Synchronous example (blocking): Copy code Js console.log("Start"); for (let i = 0; i < 1e9; i++) {} // heavy computation console.log("End"); ➡️ Output: Copy code Start End ⛔ This blocks the call stack → UI freezes or backend server becomes unresponsive. 🔹 Asynchronous JavaScript (Non-blocking behavior) Example using setTimeout: Copy code Js console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); ➡️ Output: Copy code Start End Timeout ✔ setTimeout is handled outside the call stack ✔ JavaScript continues execution without waiting 🔹 Event Loop (Execution coordinator) The Event Loop continuously monitors: Call Stack Microtask Queue Callback (Macrotask) Queue Key rule: Microtasks (Promises, async/await) always run before macrotasks (setTimeout, I/O callbacks). Interview-favorite example: Copy code Js console.log("Start"); setTimeout(() => console.log("setTimeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); ➡️ Output: Copy code Start End Promise setTimeout ✔ Promise → Microtask Queue (higher priority) ✔ setTimeout → Callback Queue 🔹 async / await (Real-world usage) Copy code Js async function fetchData() { console.log("Fetching..."); await Promise.resolve(); console.log("Done"); } fetchData(); console.log("After call"); ➡️ Output: Copy code Fetching... After call Done ✔ await pauses only the async function ✔ Does not block the call stack or event loop 🔹 Node.js Internals: libuv & Thread Pool (Production Insight) In Node.js, asynchronous tasks are handled by libuv, which provides: Event loop implementation OS-level async handling Thread pool for blocking operations Blocking operations handled by thread pool: File system (fs) Crypto DNS Compression File system example: Copy code Js const fs = require("fs"); console.log("Start"); fs.readFile("test.txt", () => { console.log("File read"); }); console.log("End"); ➡️ Output: Copy code Start End File read ✔ File I/O runs in libuv thread pool ✔ Main thread remains free to handle #JavaScript #EventLoop #NodeJS #libuv #ThreadPool #AsynchronousJavaScript #BackendDevelopment #SoftwareEngineering #LearningInPublic #InterviewPrep
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