🔍 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴? 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
Understanding Hoisting in JavaScript: How it Affects Your Code
More Relevant Posts
-
⚙️✨ 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
-
💡JavaScript Series | Topic 2 | Part 1 — JavaScript’s Type System & Coercion — The Subtle Power Behind Simplicity 👇 JavaScript’s biggest strength — flexibility — can also be its trickiest part. To write bug-free, production-grade code, you must understand how its type system and type coercion really work. 🧱 The Foundation: JavaScript’s Type System JavaScript defines 7 primitive types, each with a specific role 👇 typeof 42; // 'number' typeof 'Hello'; // 'string' typeof true; // 'boolean' typeof undefined; // 'undefined' typeof null; // ⚠️ 'object' (a long-standing JS quirk) typeof Symbol(); // 'symbol' typeof 123n; // 'bigint' ✅ Everything else — arrays, functions, and objects — falls under the object type. ⚡ Dynamic Typing in Action In JavaScript, variables can change type during execution 👇 let value = 10; // number value = "10"; // now string value = value + 5; // '105' (string concatenation!) 👉 Lesson: Dynamic typing = flexibility + danger. It saves time, but you must stay alert to implicit conversions. 🔄 Type Coercion – When JavaScript “Helps” You Type coercion happens when JavaScript automatically converts types during comparisons or operations. console.log(1 + "2"); // '12' (number → string) console.log(1 - "2"); // -1 (string → number) console.log(1 == "1"); // true (loose equality) console.log(1 === "1"); // false (strict equality) ✅ Use === (strict equality) to avoid hidden coercion bugs. ⚠️ JavaScript tries to be helpful — but that “help” can silently break logic. 🧠 Why It Matters Understanding JS types makes your code: 🧩 More predictable ⚙️ Easier to debug 🚀 Faster in performance (engines optimize consistent types) 💬 My Take: JavaScript’s type system isn’t broken — it’s powerful but misunderstood. Mastering coercion and types is what separates good developers from great engineers. 👉 Follow Rahul R Jain for real-world JavaScript & React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #TypeCoercion #WebDevelopment #Coding #TypeSystem #NodeJS #ReactJS #NextJS #TypeScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain
To view or add a comment, sign in
-
✍️ JavaScript Tip: Optional Chaining (?.) If you’ve ever tried accessing something deep inside an object and got an error like: Cannot read property 'x' of undefined You're not alone 😅 This happens a lot when you're not sure if a value exists. For example, you’re trying to access user.profile.picture.url, but profile might be missing or picture might not be there. Without checking every step, JavaScript throws an error and your app can crash ❌ It use to happen to me too🥲 I once ran into a bug while building a simple post form where users could optionally add tags through a tags input. Everything was working fine but form submission was slow. Then decided to optimize the image upload flow by compressing images on the front end and uploading them all at once to Cloudinary, which made the form submit faster. While testing, I filled only the required fields and left out the optional tags. That’s when the form crashed. The backend expected a string to split into an array, but since tags was undefined, calling .split(',') threw an error. A simple fix like tags?.split(',') || [] would’ve handled it safely. That’s when optional chaining really made sense to me. ✅ You might be wondering what optional chaining really does to safeguard your code. Let me explain😎 Optional chaining (?.) lets you safely access nested values without having to check each level manually. Instead of writing: if (user && user.profile && user.profile.picture) { // ... } You can simply write: user?.profile?.picture?.url If anything in that chain doesn’t exist (undefined or null), JavaScript just returns undefined instead of crashing 😌 🤔 What’s Really Happening When you use optional chaining (?.), JavaScript checks step by step: 1. Does the part before ?. exist? 2. If yes, it continues 3. If not, it stops and returns undefined It skips the rest of the chain once something is missing. No errors. No drama ✅ 😀 A Simple Example const user = { name: "Ferdinand" }; console.log(user?.profile?.email); // undefined, no error In this case, since profile doesn't exist, JavaScript doesn't even try to check email. It just returns undefined safely. 🔥 When You Should Use It ✅ When working with API data ✅ When reading optional user input ✅ When you’re unsure if certain data exists ✅ When accessing settings or config data It makes your code shorter, cleaner, and safer. ⚠️ But watch out Optional chaining only stops on undefined or null. If a value is false, 0, or an empty string (""), it continues as normal. Also, don’t use it everywhere blindly. It can hide bugs if you're not sure what should or shouldn't be optional 🤨
To view or add a comment, sign in
-
-
💡JavaScript Series | Topic 3 | Part 1 — JavaScript Scoping and Closures 👇 Understanding how scope and closures work isn’t just useful — it’s fundamental to writing predictable, bug-free JavaScript. These concepts power everything from private variables to callbacks and event handlers. Let’s break it down 👇 🧱 Lexical Scope — The Foundation JavaScript uses lexical (static) scoping, which means: ➡️ The structure of your code determines what variables are accessible where. Think of each scope as a nested box — variables inside inner boxes can “see outward,” but outer boxes can’t “peek inward.” 👀 // Global scope — always visible let globalMessage = "I'm available everywhere"; function outer() { // This is a new scope "box" inside global let outerMessage = "I'm available to my children"; function inner() { // The innermost scope let innerMessage = "I'm only available here"; console.log(innerMessage); // ✅ Own scope console.log(outerMessage); // ✅ Parent scope console.log(globalMessage); // ✅ Global scope } inner(); // console.log(innerMessage); // ❌ Error: Not accessible } // console.log(outerMessage); // ❌ Error: Not accessible outer(); 🧠 Key takeaway: You can look outward (from inner to outer scopes), but never inward (from outer to inner). ⚙️ var vs let vs const — The Scope Trap How you declare variables changes their visibility: Keyword Scope Type Notes var Function-scoped Leaks outside blocks (❌ risky) let Block-scoped Safer, modern choice (✅ recommended) const Block-scoped Immutable, great for constants Example 👇 if (true) { var a = 1; // function scoped let b = 2; // block scoped } console.log(a); // ✅ 1 console.log(b); // ❌ ReferenceError ✅ Best Practice: Always use let or const — they prevent scope leakage and weird bugs. 🧠 Why This Matters 🔒 Helps create encapsulation and private variables. 🧩 Avoids naming conflicts and unexpected overwrites. ⚙️ Powers closures, async callbacks, and higher-order functions. 💬 My Take: Mastering scope is like mastering the rules of gravity in JavaScript — it’s invisible, but it controls everything you build. Up next: Part 2 — Closures: How Functions Remember 🧠 👉 Follow Rahul R Jain for real-world JavaScript & React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #Closures #Scope #LexicalScope #WebDevelopment #Coding #ReactJS #NodeJS #NextJS #TypeScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
Why does this act weird in JavaScript? 💭 Ever wondered why this in JavaScript sometimes feels possessed? Let’s break the magic (and madness) behind it 👇 this depends on how a function is called, not where it’s written. JavaScript doesn’t decide the value of this when you write the function, but only when you call it — and how you call it changes what this means. **Some definitions that are needed to understand the post ** what is Binding is the way JavaScript decides what this refers to when a function is called. 👉 In short: Binding = the connection between this and its value (object/global/undefined). 🧩 Types of Binding Dynamic binding → this depends on how the function is called. Lexical binding → this is inherited from where the function was written (arrow functions). Manual binding → you set this yourself using .call(), .apply(), or .bind(). 💡 How this Behaves in Every Case (JavaScript) 1️⃣ Global Scope console.log(this===window) In browsers: this = window In strict mode: still window (only inside functions it becomes undefined) this refers to the global object. 2️⃣ Inside a Normal Function Non-strict mode: this = window Strict mode: this = undefined Because the function isn’t called by any object — so this defaults to global (or undefined in strict mode). 3️⃣ Inside an Arrow Function Non-strict mode: this = window Strict mode: this = undefined Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (where they were created). 🧠 In simple words: Arrow functions use the this value of their outer function — they never create a new one. 4️⃣ Inside an Object Method this refers to the object that owns the method → user. That’s called dynamic binding (decided by how it’s called). 🔶 Normal function is automatic dynamicly binding by js which this inside it refers to the object . 🔶Arrow function dynamic is lexical binding which means only lexical scops like global ,function or block scoop that inherit it's this value from it so this will not refer to the object 🔶Nested functions When a function is declared inside another function, the inner normal function doesn’t automatically inherit this from the outer one. 🧠 In simple words: Each normal function has its own this — it doesn’t care about its parent. 📉 Result: In non-strict mode → this = window In strict mode → this = undefined because the inner function isn’t called by any object that means no dynamic binding for the inner One obj =>one normal fun So what are the solutions that we have ?? 🅰️ Arrow function as an inner function because of it's lexical binding to inherit this value from the outer() 🅱️ Manual binding to force the inner function in the normal form (Not arrow) to refer to the outer #JavaScript #CodingTips #Frontend #WebDevelopment #LearningJS #WomenInTech #SamiaLearnsJS
To view or add a comment, sign in
-
-
Day 18/100 Day 9 of JavaScript Arrow Functions in JavaScript — A Modern & Cleaner Way to Write Functions In modern JavaScript (ES6+), arrow functions provide a shorter and more elegant way to write functions. They make your code concise and improve readability, especially when working with callbacks or array methods like .map(), .filter(), and .reduce(). What is an Arrow Function? An arrow function is simply a compact syntax for defining functions using the => (arrow) symbol. Syntax: const functionName = (parameters) => { // block of code }; It’s equivalent to: function functionName(parameters) { // block of code } Example: Traditional vs Arrow Function Traditional Function: function add(a, b) { return a + b; } console.log(add(5, 3)); // Output: 8 Arrow Function: const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8 Cleaner and shorter! Key Features of Arrow Functions : No function keyword — Makes your code concise. Implicit return — If the function body has only one statement, the result is automatically returned (no need for return). Lexical this binding — Arrow functions don’t have their own this. They inherit this from the parent scope — making them great for use inside callbacks or class methods. Example: Lexical this function Person() { this.name = "Appalanaidu"; setTimeout(() => { console.log(this.name); // Works perfectly! }, 1000); } new Person(); // Output: Appalanaidu If we had used a regular function inside setTimeout, this would be undefined or refer to the global object — not the instance. Arrow functions solve that issue neatly. Quick Recap Shorter syntax Implicit return Lexical this Great for callbacks Example Use Case: Array Mapping const numbers = [1, 2, 3, 4]; const squares = numbers.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16] Arrow functions make such one-liners elegant and easy to read! Final Thought Arrow functions are not just syntactic sugar — they’re a modern JavaScript feature that simplifies code and makes your logic cleaner. Once you start using them, you’ll rarely go back to the old way! #10000coders
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 a Javascript L1 & L2 round the following questions can be asked from interviewer. Learn all ques for free on interviewdepth.com 1. What is the difference between 'Pass by Value' and 'Pass by Reference'? 2. What is the difference between map and filter ? 3. What is the difference between map() and forEach() 4. What is the difference between Pure and Impure functions? 5. What is the difference between for-in and for-of ? 6. What are the differences between call(), apply() and bind() ? 7. List out some key features of ES6 ? 8. What’s the spread operator in javascript ? 9. What is rest operator in javascript ? 10. What are DRY, KISS, YAGNI, SOLID Principles ? 11. What is temporal dead zone ? 12. Different ways to create object in javascript ? 13. Whats the difference between Object.keys,values and entries 14. Whats the difference between Object.freeze() vs Object.seal() 15. What is a polyfill in javascript ? 16. What is generator function in javascript ? 17. What is prototype in javascript ? 18. What is IIFE ? 19. What is CORS ? 20. What are the different datatypes in javascript ? 21. What are the difference between typescript and javascript ? 22. What is authentication vs authorization ? 23. Difference between null and undefined ? 24. What is the output of 3+2+”7” ? 25. Slice vs Splice in javascript ? 26. What is destructuring ? 27. What is setTimeOut in javascript ? 28. What is setInterval in javascript ? 29. What are Promises in javascript ? 30. What is a callstack in javascript ? 31. What is a closure ? 32. What are callbacks in javascript ? 33. What are Higher Order Functions in javascript ? 34. What is the difference between == and === in javascript ? 35. Is javascript a dynamically typed language or a statically typed language 36. What is the difference between Indexeddb and sessionstorage ? 37. What are Interceptors ? 38. What is Hoisting ? 39. What are the differences let, var and const ? 41. Differences between Promise.all, allSettled, any, race ? 42. What are limitations of arrow functions? 43. What is difference between find vs findIndex ? 44. What is tree shaking in javascrip 45. What is the main difference between Local Storage and Session storage 46. What is eval() 47. What is the difference between Shallow copy and deep copy 48. What are the difference between undeclared and undefined variables 49. What is event bubbling 50. What is event capturing 51. What are cookies 52. typeOf operator 53. What is this in javascript and How it behaves in various scenarios 54. How do you optimize the performance of application 55. What is meant by debouncing and throttling #javascriptdeveloper #reactjs #reactnative #vuejsdeveloper #angular #angulardeveloper
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 Ever wondered how JavaScript handles tasks without blocking the main thread? That’s where 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 come into play! ⚙️ 🧩 What is a Callback Function? 𝐀 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐢𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐧 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭 𝐭𝐨 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 — 𝐚𝐧𝐝 𝐢𝐬 𝐢𝐧𝐭𝐞𝐧𝐝𝐞𝐝 𝐭𝐨 𝐛𝐞 “𝐜𝐚𝐥𝐥𝐞𝐝 𝐛𝐚𝐜𝐤” 𝐥𝐚𝐭𝐞𝐫 𝐛𝐲 𝐭𝐡𝐚𝐭 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 💡 Since functions in JavaScript are First-Class Citizens, they can be treated like values — passed around, returned, or assigned to variables. 📖 Think of it like this: You give function 𝐗 the responsibility to call function𝐘 later. So,𝐘becomes the callback of𝐗. ----------------------------------------------------- ⏱️ Callbacks in Action: Handling Asynchronous Operations JavaScript is 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝, but callbacks allow it to perform non-blocking tasks like API calls, timers, or event handling. Here’s a simple example 👇 console.log("Start"); setTimeout(() => { console.log("⏰ This runs after 2 seconds"); }, 2000); console.log("End"); 🧠 Output: Start End ⏰ This runs after 2 seconds 💬 Explanation: When 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 is called, the callback goes into the Web API environment. The JS engine keeps running other code (non-blocking). After the timer expires, the callback moves to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞. It’s executed only when the Call Stack is empty, ensuring smooth asynchronous flow. 𝐓𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐚𝐠𝐢𝐜 𝐨𝐟 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 𝐞𝐧𝐚𝐛𝐥𝐢𝐧𝐠 𝐚𝐬𝐲𝐧𝐜 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐢𝐧 𝐚 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝 𝐰𝐨𝐫𝐥𝐝! ✨ -------------------------------------------------- 🔒 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 + 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 = 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐆𝐨𝐥𝐝 💬 Here’s a classic interview problem 👇 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: If you try to use a global counter variable, you risk having it modified by other parts of the code. A better solution is needed to keep the counter private and persistent. 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 (𝐂𝐥𝐨𝐬𝐮𝐫𝐞): By creating a function that wraps the counter and the event listener attachment, the event handler (the callback) forms a closure over the local variable (count). 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤() { 𝐥𝐞𝐭 𝐜𝐨𝐮𝐧𝐭 = 0; 𝐝𝐨𝐜𝐮𝐦𝐞𝐧𝐭.𝐠𝐞𝐭𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐁𝐲𝐈𝐝("𝐛𝐭𝐧").𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫("𝐜𝐥𝐢𝐜𝐤", 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧() { 𝐜𝐨𝐮𝐧𝐭++; 𝐜𝐨𝐧𝐬𝐨𝐥𝐞.𝐥𝐨𝐠("𝐁𝐮𝐭𝐭𝐨𝐧 𝐜𝐥𝐢𝐜𝐤𝐞𝐝", 𝐜𝐨𝐮𝐧𝐭, "𝐭𝐢𝐦𝐞𝐬"); }); } 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤(); 🧩 Explanation: The inner callback function forms a closure over the variable count. Even after handleClick() finishes executing, count stays alive in the callback’s Lexical Environment. This keeps the counter private, persistent, and secure — no memory Leaks. #JavaScript #WebDevelopment #LearningInPublic #NamasteJavaScript #FrontendDevelopment #CodingJourney
To view or add a comment, sign in
-
#CodingTips #BackendDevelopment #WebDevelopment #Nodejs #Expressjs #SoftwareEngineering #SoftwareDevelopment #Programming The reduce() is one of powerful #JavaScript method and also one of most confusing JavaScript method that even many developers sometimes misunderstand. the JavaScript reduce() method has many functionalities including: - It can be used for grouping objects within an array - It can be used for optimizing performance by replacing filter() method with reduce() in many circumstances - It can be used for summing an array - It can be used for flatten a list of arrays And many more. Of course I am not gonna explain it one by one. But here, I am gonna explain it to you generally, about how does reduce() method work in JavaScript? Now, let's take a look at the code snippet below. At the beginning of iterations, the accumulator (written with the sign {}) starts with the initial empty object. It's just {} (an empty object). While the currentItem is the object with the data inside like: {car_id: 1, etc}. Assume currentItem is: {car_id: 1, etc}, then when below code is executed: if (acc[currentItem.car_id]) Its like the accumulator {} will check if the currentItem.car_id, which is 1 is exist or not?. But because at the beginning is just only {} (an empty object), then it will execute the code below: acc[currentItem.car_id] = [currentItem]; It means it will generate a group of current car_id 1 with its object data, related to car id 1. So, the accumulator becoming like this: { 1: [ // coming from acc[currentItem.car_id {car_id: 1, etc} // coming from currentItem ] } And looping... Still looping until it will check again if acc[currentItem.car_id] (which is car_id is 1 for example) is exist. Because it exist, then acc[currentItem.car_id].push(currentItem); So the result will be like below: { 1: [ {car_id: 1, etc} // coming from currentItem {car_id: 1, etc} // new coming from current item ] } And it always iterate all the data until reach out the end of records. And once it's done, the final result will be like below: { 1: [ {car_id: 1, etc} {car_id: 1, etc} ], 2: [ {...}, {...}, ... ] 3: [ {...}, {...}, ... ] ... } I hope this explanation helps you to understand how JavaScript reduce() method works? Back then, I had a nightmare and difficulties to understand it, but when I know it, I started to realize how powerful it is.
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