🏹 𝐓𝐡𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐅𝐚𝐜𝐞-𝐎𝐟𝐟: 𝐀𝐫𝐫𝐨𝐰 vs. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 If the this keyword feels like a riddle wrapped in a mystery, you aren’t alone! It’s one of the most confusing parts of JavaScript, but the secret lies in how you define your functions. Here is the breakdown of the two heavyweights and exactly when to use them: 1. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐃𝐮𝐨) 🔄 𝐒𝐲𝐧𝐭𝐚𝐱: function doSomething() { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is dynamic. The value of this depends entirely on how the function is called (the caller). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Object methods or constructor functions where you need to access the object's own properties. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these when you want the function to have its own context. 2. 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐒𝐥𝐞𝐞𝐤 𝐒𝐡𝐚𝐫𝐩𝐬𝐡𝐨𝐨𝐭𝐞𝐫) 🎯 𝐒𝐲𝐧𝐭𝐚𝐱: const doSomething = () => { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is lexical. They don’t have their own this. Instead, they "inherit" it from the surrounding code (the parent scope). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Callbacks (like .map() or .filter()), closures, and preserving context inside setTimeout. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these to keep your code concise and to avoid the "that = this" or .bind(this) hacks of the past. 🚩 𝐖𝐡𝐞𝐧 𝐍𝐎𝐓 𝐭𝐨 𝐮𝐬𝐞 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬: Methods in Objects: If you use an arrow function as an object method, this will point to the global window/undefined instead of the object itself! Event Listeners: If you need this to represent the element that was clicked, stick to a regular function. 𝐓𝐡𝐞 𝐆𝐨𝐥𝐝𝐞𝐧 𝐑𝐮𝐥𝐞: Use Arrow Functions by default for their clean syntax and predictable context in callbacks. Switch to Regular Functions only when you specifically need a dynamic this (like in methods or constructors). Are you still using .bind(this) in 2026, or have you fully embraced the arrow? Let’s settle the debate below! 👇 #JavaScript #CodingTips #WebDev #SoftwareEngineering #ArrowFunctions #ProgrammingLogic #CleanCode
JavaScript Functions: Arrow vs Regular
More Relevant Posts
-
🚀 5 Tricky JavaScript Output Questions (Closures & Scope) Let’s test your JS fundamentals 👇 Try to guess the output before checking answers. 1️⃣ for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 2️⃣ let a = 10; (function () { console.log(a); let a = 20; })(); 3️⃣ function foo() { console.log(x); var x = 10; } foo(); 4️⃣ const obj = { a: 10, getA() { return this.a; } }; const fn = obj.getA; console.log(fn()); 5️⃣ console.log(typeof typeof 1); Answers below 👇 1️⃣ 3 3 3 (var is function-scoped, same reference) 2️⃣ ReferenceError (Temporal Dead Zone for `let`) 3️⃣ undefined (var hoisting without initialization) 4️⃣ undefined (`this` is lost when function is detached) 5️⃣ "string" (typeof 1 → "number", typeof "number" → "string") If you can explain *why*, you’re interview-ready 💯 #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
**JavaScript Closures Demystified: No More Anxiety!** If you’ve ever felt your heart skip a beat when someone mentions “closures” in JavaScript, you’re not alone. Many developers find the concept intimidating—but it doesn’t have to be. In simple terms, a **closure** is a function that “remembers” the variables from its outer scope, even after that outer function has finished running. Think of it like a backpack: when a function is created, it carries a snapshot of the environment it was born in. Why does this matter? - **Data Privacy**: Closures help create private variables that can’t be accessed from outside. - **State Preservation**: They’re essential in callbacks, event handlers, and functional programming patterns. - **Modular Code**: Enable patterns like the Module Pattern, keeping your code organized and secure. Example snippet: ```javascript function createCounter() { let count = 0; return function() { count++; console.log(count); }; } const counter = createCounter(); counter(); // 1 counter(); // 2 // `count` is protected, accessible only via the returned function. ``` Closures aren’t magic—they’re a natural part of how JavaScript handles scope. Once you grasp the idea of “functions with memories,” a lot of advanced JS patterns start to make sense. So next time you hear “closure,” take a deep breath. It’s just a function carrying its little backpack of variables. #JavaScript #WebDevelopment #CodingTips #LearnToCode #SoftwareEngineering
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 Have you ever seen JavaScript behave correctly… but still give the wrong output? 🤔 𝘉𝘦𝘧𝘰𝘳𝘦 𝘴𝘤𝘳𝘰𝘭𝘭𝘪𝘯𝘨, 𝘨𝘶𝘦𝘴𝘴 𝘵𝘩𝘦 𝘰𝘶𝘵𝘱𝘶𝘵 𝘰𝘧 𝘵𝘩𝘪𝘴 𝘴𝘪𝘮𝘱𝘭𝘦 𝘤𝘰𝘥𝘦 𝚏𝚘𝚛 (𝚟𝚊𝚛 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗘𝘅𝗽𝗹𝗲𝗰𝘁𝗲𝗱 1, 2, 3 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗿𝗲𝘀𝘂𝗹𝘁 4,4,4 𝗧𝗵𝗶𝘀 𝗶𝘀 𝗮 𝗰𝗹𝗼𝘀𝘂𝗿𝗲 𝗯𝘂𝗴 — 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗺𝗺𝗼𝗻 (𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴) 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗽𝗶𝘁𝗳𝗮𝗹𝗹𝘀. 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 • var is function-scoped • setTimeout creates a closure • All callbacks reference the same variable i • When they execute, the loop has already finished Closures don’t capture values — they capture references. 𝗧𝗵𝗲 𝗙𝗶𝘅 𝚏𝚘𝚛 (𝚕𝚎𝚝 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝘄𝗼𝗿𝗸𝘀: • let is block-scoped • Each iteration gets its own binding • Each closure remembers a different i 𝗬𝗼𝘂’𝗹𝗹 𝘀𝗲𝗲 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝗶𝗻: • Event handlers • Async loops • API callbacks • Timers • React effects If you don’t understand closures, You don’t see the bug — you just debug longer. #JavaScript #JSFundamentals #Closures #FrontendDevelopment #WebDevelopment #BugFixing #ReactJS #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Stop Guessing How JavaScript Works: The Event Loop Explained Ever wondered why JavaScript is "single-threaded" but can still handle thousands of concurrent tasks without breaking a sweat? The secret isn't magic; it's the Event Loop. 🎡 If you want to master asynchronous programming, you have to understand how these four pieces play together: 1. The Call Stack 📚 This is where the engine tracks what function is currently running. It’s a LIFO (Last In, First Out) structure. If the stack is busy, nothing else happens. 2. Web APIs 🌐 When you call a setTimeout, a fetch request, or a DOM event, JavaScript "hands off" these tasks to the browser (or Node.js). This keeps the main thread free. 3. The Callback Queue (Task Queue) 📥 Once a Web API finishes its job, the callback (the code you want to run) moves here to wait for its turn. 4. The Event Loop 🔄 The "Gatekeeper." It has one simple job: Look at the Call Stack. If the Stack is empty, take the first task from the Queue and push it onto the Stack. 💡 Why does this matter? Have you ever seen a UI freeze during a heavy calculation? That’s because the Call Stack is clogged, and the Event Loop can't push the "render" or "click" tasks from the queue. Pro Tip: Always remember that Microtasks (like Promises) have a "VIP pass." They get executed before the standard Macrotasks (like setTimeout), even if the timer has already expired! #JavaScript #WebDevelopment #ProgrammingTips #Frontend #SoftwareEngineering #EventLoop
To view or add a comment, sign in
-
Why does 0 == false return true in JavaScript? 😵 If this confuses you, you're not alone. I wrote a guide explaining == vs === and how to avoid common pitfalls that trip up even experienced developers. Link below 👇 https://lnkd.in/dGP2aJZr #JavaScript #CodingTips #WebDev
To view or add a comment, sign in
-
🤯 JavaScript Currying: Why does this function keep returning functions? Ever seen code like this and thought “Who hurt you?” 👇 add(1)(2)(3) Why not just write add(1, 2, 3) like a normal human? 😅 Welcome to Currying in JavaScript 👇 🧠 What is Currying? Currying is a functional programming technique where a function that takes multiple arguments is broken into a chain of functions, each taking one argument at a time. const add = a => b => c => a + b + c; add(1)(2)(3); // 6 Each function remembers the previous value using closures. Yes, JavaScript never forgets… 🤔 Why should you care? Because currying helps you write: ✅ Reusable code ✅ Cleaner & readable logic ✅ Partial application (fix some arguments now, pass the rest later const multiply = a => b => a * b; const double = multiply(2); double(5); // 10 const triple = multiply(3); triple(5); // 15 Write once, reuse everywhere 🔥 ⚛️ Where do we actually use this? If you’re a React / Redux developer, you’re already using currying 👀 ⚠️ Currying ≠ Partial Application Quick reminder: ⚛️ Currying → f(a)(b)(c) ⚛️ Partial application → pre-fill some arguments and reuse the function Different tools, same productivity boost 🚀 Middleware, event handlers, utility functions… it’s everywhere. #ReactJS #JavaScript #WebDevelopment #Frontend #MERN #ReactHooks #CleanCode #JavaScript #WebDevelopment #FrontendMagic #CodeWithFun #TechExplainedSimply #mernstack #mern #react #js #JavaScript #WebDevelopment #CodingHumor #FrontendDevelopment #TechEducation #ProgrammingFun #LearnToCode #CodeNewbie #DeveloperCommunity
To view or add a comment, sign in
-
JavaScript Fundamentals - Part 3 Hoisting It is behavior of processing declarations before executing code. In simple terms: - JavaScript knows about variables and functions before running the code - This happens during the memory creation phase of an execution context So, hoisting is not moving code upward rather its preparing memory upfront. Why hoisting exists - its is side effect of how JS creates execution contexts. Before execution: - memory is allocated - identifiers are registered - scope is set up This allows: - function calls before their definition - predictable scope resolution Hoisting by Declaration Type var hoisting console.log(a); var a = 10; What happens: - a is hoisted - initialized with undefined - assigned 10 during execution So, console.log(a); // undefined Function Declaration Hoisting sayHi(); function sayHi(){ console.log("Hi"); } What happens: - entire function is hoisted - function can be called before declaration let and const Hoisting console.log(b); let b = 20; // ReferenceError: Cannot access 'b' before initialization What happens: - b is hoisted - but not initialized - exists in TDZ - Function Expressions sayHello(); var sayHello = function() { console.log("Hello"); }; What happens; - sayHello is hoisted as undefined - function body is not hoisted Result: TypeError: sayHello is not a function TDZ -it is the time between entering a scope and initializing let or const variable - variable exists - but cannot be accessed - prevents accidental usage before declaration TDZ is not special zone in memory, it is a state of a binding between hoisting and initialization { // TDZ starts console.log(a); //ReferenceErrror let a = 10; // TDZ ends } So, based on our above details, how can you describe Hoisting in one line ? Please follow for Part 4 updates. 👍 #javascriptfundamentals #uideveloper #corejs
To view or add a comment, sign in
-
🤔 Ever wondered why arrow functions behave differently from normal functions in JavaScript? They look shorter, but they change the rules. 🧠 JavaScript interview question What are arrow functions and how are they different from normal functions? ✅ Short answer • Arrow functions are a shorter ES6 syntax • They do not have their own this • They are not constructors • They don’t have arguments, prototype, or new.target 🔍 A bit more detail 👉 Lexical this (the big one) Arrow functions capture this from where they are defined, not how they’re called. const obj = { count: 0, inc() { setTimeout(() => { this.count++; }, 100); } }; No .bind(this) needed. The arrow keeps the outer this. 👉 No own arguments Use rest parameters instead: const sum = (...nums) => nums.reduce((a, b) => a + b, 0); 👉 Not constructible new (() => {}) // ❌ TypeError Arrow functions have no prototype and can’t be used with new. 👉 Implicit returns const double = x => x * 2; Block body? You must return. ⚠️ When to avoid arrow functions • Object or prototype methods that rely on dynamic this • Constructors or generator functions • Event handlers that expect this to be the DOM element const obj = { total: 0, add() { this.total++; // ✅ correct } }; 🚀 When arrow functions shine • Callbacks (setTimeout, promises) • Array methods (map, filter, reduce) • Short utility functions • Preserving outer this in classes 🧩 Mental checklist • Need your own this? → normal function • Need outer this? → arrow function • Need new, arguments, or prototype? → normal function 💡 Arrow functions aren’t just shorter syntax, they change semantics. #javascript #frontend #webdevelopment #react #interviewprep #programming
To view or add a comment, sign in
-
🤔 Ever wondered how JavaScript finds obj.prop when it’s not on the object itself? That “search path” is the prototype chain. 🧠 JavaScript interview question How does the prototype chain work, and what is “shadowing”? ✅ Short answer • JS first checks own properties on the object • If not found, it follows [[Prototype]] (aka __proto__) upward • The first match wins • Adding the same property on a child shadows the one higher in the chain 🔍 A bit more detail • Reads use the chain: obj.prop → own props → prototype → prototype’s prototype → … → Object.prototype → null • Writes are different: obj.prop = value usually creates/updates an own property on obj (it does not “climb” to update the prototype) • Methods found on the prototype run with this === obj (the receiver), not the prototype • Getters/setters on a prototype can intercept reads/writes • Enumeration is different: for...in walks inherited enumerable keys too, while Object.keys() returns only own enumerable keys 💻 Example: lookup + shadowing const A = { greet() { return "from A"; } }; const B = Object.create(A); const C = Object.create(B); console.log(C.greet()); // "from A" C.greet = function () { return "from C"; }; // shadow A.greet console.log(C.greet()); // "from C" 💻 Example: assignment does NOT update the prototype const base = { x: 1 }; const child = Object.create(base); child.x = 2; console.log(child.x, base.x); // 2, 1 #javascript #frontend #webdevelopment #interviewprep #prototypalinheritance #react #programming
To view or add a comment, sign in
-
So, closures are a thing in JavaScript. They're basically functions that remember stuff from their outer scope - and that's pretty cool. It's like a function has a memory, you know? A closure is a function that can access variables from its outer scope, even after the outer function has finished executing - which is wild. Here's the deal: when a function is defined inside another function, it's like they're related or something. The inner function has access to the outer function's variables, which is pretty handy. And when the outer function finishes executing, the inner function can still access its variables - it's like they're connected, you know? For instance, check out this example: ```javascript function createCounter() { let count = 0; return function increment() { count++; console.log(count); }; } ``` In this case, the `increment` function remembers the `count` variable from its outer scope - it's like it has a reference to it or something. Closures are used in a lot of JavaScript concepts, including React Hooks - so understanding them is pretty important. If you don't get closures, you might end up with bugs in your code, and that's no fun. So, what's the key to understanding closures? It's simple: a function remembers its outer scope - that's it. You can use closures to create private variables, which is pretty useful. For example: ```javascript function createBankAccount(initialBalance) { let balance = initialBalance; return { deposit(amount) { balance += amount; return balance; }, withdraw(amount) { if (amount > balance) { throw new Error('Insufficient funds'); } balance -= amount; return balance; }, getBalance() { return balance; } }; } ``` In this example, the `balance` variable is private - it can only be accessed through the returned methods, which is like a security feature or something. Anyway, that's closures in a nutshell. Check out this article for more info: https://lnkd.in/gsbBxJf5 #javascript #closures #reacthooks #coding
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