🚨 JavaScript “this” Trap — Arrow Function vs Regular Function const counter = { value: 42, show: () => this.value, }; console.log(counter.show.call({ value: 100 })); // undefined ❗ 💡 What’s happening? Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (usually the global scope). So even when we try to override this using .call(), .apply(), or .bind(), it doesn’t work. 👉 That’s why the result is undefined instead of 100. ✅ When to use Arrow Functions: • When you want to preserve the outer this (e.g., inside callbacks, closures) • In React functional components or array methods (map, filter, etc.) • When you don’t need dynamic context ❌ When NOT to use Arrow Functions: • Object methods that rely on this • Constructors (they can’t be used with new) • Event handlers where this refers to the element • When you need .call(), .apply(), or .bind() 🔥 Fix the issue: const counter = { value: 42, show() { return this.value; }, }; console.log(counter.show.call({ value: 100 })); // 100 ✅ ⚡ Key Takeaway: Arrow functions are not a replacement for regular functions — they’re a different tool. Use them wisely. Misusing them can silently break your logic. #JavaScript #WebDevelopment #Frontend #MERN #CodingTips #CleanCode #reactjs #nodejs
JavaScript 'this' Trap: Arrow Function vs Regular Function
More Relevant Posts
-
🚀 CSS is getting smarter — almost like JavaScript!Did you know that modern CSS now supports conditional logic (like IF statements)? 🤯While we still don’t have a direct if...else syntax, features like: ✅ @supports → Apply styles if the browser supports a feature ✅ @container → Apply styles if the parent size matches ✅ :has() → Style elements if they contain specific content ✅ @media → Apply styles if screen conditions match…are making CSS more powerful than ever. 💡 Example: Default (acts like ELSE).card { background: white; }Condition (acts like IF)@media (max-width: 600px) { .card { background: black; } }✨ This shift is huge for frontend developers — less dependency on JavaScript for UI logic and more control directly in CSS.The future? Real @when / @else support is already being discussed 👀What do you think — will CSS replace small JS logic in UI soon?#CSS #WebDevelopment #Frontend #JavaScript #Programming #Developer #ReactJS
To view or add a comment, sign in
-
-
⚡ JavaScript Performance: Common Pitfalls Avoid these performance killers: 1. **DOM manipulation in loops** ```js // Bad for (let i = 0; i < 1000; i++) { document.body.appendChild(createElement()); } // Good const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { fragment.appendChild(createElement()); } document.body.appendChild(fragment); ``` 2. **Unnecessary re-renders in React** ```js // Use useMemo, useCallback, React.memo ``` 3. **Blocking the main thread** ```js // Use Web Workers for heavy computation ``` What's your biggest JavaScript performance fix? #JavaScript #Performance #Frontend #Optimization
To view or add a comment, sign in
-
Stop guessing the order of your console.logs. 🛑 JavaScript is single-threaded. It has one brain and two hands. So, how does it handle a heavy API call, a 5-second timer, and a button click all at once without catching fire? It’s all about the Event Loop, but specifically, the "VIP treatment" happening behind the scenes. The Two Queues You Need to Know: 1. The Microtask Queue (The VIP Line) 💎 What lives here: Promises (.then), await, and MutationObserver. The Rule: The Event Loop is obsessed with this line. It will not move on to anything else until this queue is bone-dry. If a Promise creates another Promise, JS stays here until they are all done. 2. The Macrotask Queue (The Regular Line) 🎟️ What lives here: setTimeout, setInterval, and I/O tasks. The Rule: These tasks are patient. The Event Loop only picks one at a time, then goes back to check if any new VIPs (Microtasks) have arrived. The "Aha!" Moment Interview Question: What is the output of this code? (Most junior devs get this wrong). JavaScript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); The Reality: 1. Start (Sync) 2. End (Sync) 3. Promise (Microtask - Jumps the line!) 4. Timeout (Macrotask - Even at 0ms, it waits for the VIPs) The Pro-Tip for Performance 💡 If you have a heavy calculation, don't wrap it in a Promise thinking it makes it "background." It’s still on the main thread! Use Web Workers if you really want to offload the heavy lifting. Does the Event Loop still confuse you, or did this click? Let's discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🔍 JavaScript Quirk: == vs === (this will surprise you) Most devs say: 👉 “Always use ===” But do you know WHY? 👇 console.log(0 == false); console.log("" == false); console.log(null == undefined); 💥 Output: true true true Wait… WHAT? 😳 Why this happens? Because == does type coercion 👉 It converts values before comparing Step by step: ✔ false → 0 ✔ "" → 0 So internally: 0 == 0 // true 👉 Special case: null == undefined → true (but NOT equal to anything else) Now compare with === 👇 console.log(0 === false); console.log("" === false); 💥 Output: false false Because === checks: ✔ Value ✔ Type No conversion. No surprises. Now the WEIRDEST one 🤯 console.log([] == false); 💥 Output: true Why? [] → "" → 0 false → 0 👉 0 == 0 Yes… JavaScript really did that 😅 💡 Takeaway: ✔ == tries to be “smart” (and fails) ✔ === is strict and predictable ✔ Use === by default 👉 "Always use ===" is not a rule… It’s survival advice. 🔁 Save this (you’ll forget this later) 💬 Comment "===" if this clicked ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (setTimeout + loop) You write this code: for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } You expect: 1 2 3 But you get: 4 4 4 This happens because of closure 📌 What is a Closure? 👉 A closure is a function along with its lexical environment. Not clear? No problem. Here’s a simpler version: 👉 A closure is a function along with the variables it remembers from where it was created. In this case: The function inside setTimeout 👉 remembers the SAME i variable And when it executes: 👉 Loop has already finished → i = 4 So all logs print: 4, 4, 4 How to fix it? ✔ Use let (creates a new variable per iteration) for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔ Or create a new scope manually for (var i = 1; i <= 3; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } 💡 Takeaway: ✔ Closures remember variables, not values ✔ var shares the same scope → leads to bugs ✔ let creates a new scope per iteration 👉 If you understand closures, you’ll avoid some very tricky bugs. 🔁 Save this for later 💬 Comment “closure” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
The Strategy: "The 5 JS Concepts You Must Master" 📝 JavaScript isn’t hard. Your approach is. 🧠 Most beginners get stuck in "Tutorial Hell" because they try to memorize everything. In reality, you only need to master 5 core concepts to build 80% of modern web apps. If you understand these, React and Vue will feel like a breeze. 👇 ✅ 1. The DOM (Document Object Model) Stop thinking of HTML as text. It’s a tree. Learn how to grab an element, change its color, and add a click event. ✅ 2. Array Methods (.map, .filter, .reduce) Modern web dev is just manipulating lists of data. If you can’t transform an array of "Products" into "Shopping Cart" items, you'll struggle. ✅ 3. Asynchronous JS (Promises & Async/Await) The web doesn't wait for anyone. Learn how to fetch data from an API without freezing the user’s screen. ✅ 4. Scope & Hoisting Where does your variable live? Understanding let, const, and var will save you hours of debugging "Undefined" errors. ✅ 5. ES6+ Syntax Arrow functions, destructuring, and template literals. This is the "modern" way to write clean, professional code. 💡 The Golden Rule: Don't just read about these. Open VS Code, create a script.js file, and break things until they work. What was the hardest JS concept for you to wrap your head around? Let’s help each other in the comments! 💬 #WebDevelopment #JavaScript #CodingTips #LearnToCode #Frontend
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Function Declaration vs Expression) You write this: sayHi(); function sayHi() { console.log("Hello"); } 👉 Works perfectly ✅ Now try this: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Same idea… same function… Why different behavior? This happens because of Hoisting 📌 What’s happening here? 👉 Function Declarations are fully hoisted So internally: function sayHi() { console.log("Hello"); } sayHi(); 👉 That’s why it works even before definition But for Function Expressions: const sayHello = function () {} 👉 This is treated like a variable (const) So internally: const sayHello; // not initialized (TDZ) sayHello(); // ❌ error 📌 Key Difference: ✔ Function Declaration 👉 Hoisted completely (can call before definition) ✔ Function Expression 👉 Not hoisted like function 👉 Behaves like variable 📌 Bonus case 👇 var sayHello = function () { console.log("Hello"); }; sayHello(); 👉 Works (because var is hoisted) BUT: sayHello(); // before assignment 👉 TypeError ❌ (not a function yet) 💡 Takeaway: ✔ Function declarations → fully hoisted ✔ Function expressions → behave like variables ✔ let/const → TDZ error ✔ var → undefined (then TypeError if called) 👉 Same function… different behavior based on how you write it 🔁 Save this before it confuses you again 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Concept You Might Have Heard (First-Class Functions/Citizens) You write this: function greet() { return "Hello"; } const sayHi = greet; console.log(sayHi()); // ? 👉 Output: Hello Wait… 👉 We assigned a function to a variable? 👉 And it still works? Now look at this 👇 function greet() { return "Hello"; } function execute(fn) { return fn(); } console.log(execute(greet)); // ? 👉 Passing function as argument? 👉 And calling it later? This is why JavaScript functions are called First-Class Functions 📌 What does that mean? 👉 Functions are treated like any other value 📌 What can you do with them? ✔ Assign to variables ✔ Pass as arguments ✔ Return from another function ✔ Store inside objects/arrays Example 👇 function outer() { return function () { return "Inside function"; }; } console.log(outer()()); // ? 👉 Function returning another function 📌 Why do we need this? 👉 This is the foundation of: ✔ Callbacks ✔ Closures ✔ Functional programming ✔ Event handling 💡 Takeaway: ✔ Functions are just values in JavaScript ✔ You can pass them, store them, return them ✔ That’s why they are “first-class citizens” 👉 If you understand this, you understand half of JavaScript 🔁 Save this for later 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Day 16 — Memoization in JavaScript (Boost Performance) Want to make your functions faster without changing logic? 👉 Use Memoization 🚀 --- 🔍 What is Memoization? 👉 Memoization is an optimization technique where we cache results of expensive function calls and reuse them. --- 📌 Without Memoization function slowSquare(n) { console.log("Calculating..."); return n * n; } slowSquare(5); // Calculating... slowSquare(5); // Calculating again ❌ --- ⚡ With Memoization function memoize(fn) { let cache = {}; return function (n) { if (cache[n]) { return cache[n]; } let result = fn(n); cache[n] = result; return result; }; } const fastSquare = memoize((n) => { console.log("Calculating..."); return n * n; }); fastSquare(5); // Calculating... fastSquare(5); // Uses cache ✅ --- 🧠 What’s happening? 👉 First call → calculates result 👉 Next call → returns from cache 👉 No re-computation --- 🚀 Why it matters ✔ Improves performance ✔ Avoids repeated calculations ✔ Useful in heavy computations ✔ Used in React (useMemo) --- 💡 One-line takeaway: 👉 “Don’t recompute — reuse cached results.” --- If your function is slow, memoization can make it fast instantly. #JavaScript #Performance #Memoization #WebDevelopment #Frontend #100DaysOfCode
To view or add a comment, sign in
-
Stop using JavaScript for things CSS can now do natively. 🛑 We’ve spent years adding 50kb libraries for simple UI interactions. In 2026, the browser is much smarter than we give it credit for. If you want a high-performance frontend, start replacing your JS dependencies with these Native Web APIs: Modals/Tooltips? Use the Popover API. No more z-index battles or complex state management. Sticky Headers? position: sticky and scroll-timeline (CSS) now handle what used to require heavy scroll listeners. Responsive Components? Stop using window resize listeners. Container Queries are the new standard. Dark Mode? light-dark() color function in CSS handles it natively without a "Theme Provider" wrapper. React and Node are "Kings" for logic, but Native CSS is the Queen of Performance. The goal isn't to write more code. It's to ship less JavaScript. What’s one library you’ve deleted recently because the native browser support caught up? #Frontend #CSS #WebDevelopment #Performance #CleanCode #JavaScript #ProgrammingTips
To view or add a comment, sign in
Explore related topics
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