updated solution based on feedback by Yevhen Serbyniuk how "this" works in JavaScript. the confusion: this is not consistent. it changes depending on how your function is called. arrow functions work differently than regular functions. callbacks lose context. it's a mess. why it matters: this is everywhere in JavaScript. event handlers, callbacks, class methods. if you don't understand it, you're debugging ghosts. the real issue: regular functions get this from their caller (dynamic binding). arrow functions capture this lexically from where they're defined (static binding). this fundamental difference breaks code constantly. when it breaks hardest: callbacks inside methods. event listeners in classes. promises with then(). async operations. all the places where context gets lost or wrong. the solution: understand what this should be in your context. use arrow functions if you want parent's this. use regular functions with bind() if you want explicit control. the rule: regular functions = this from caller. arrow functions = this from definition scope. know which you need. #javascript #typescript #webdevelopment #buildinpublic #reactjs
Understanding JavaScript's this Keyword
More Relevant Posts
-
Stop using || for your Boolean defaults! 🛑 Ever passed false to a function, only to have your code treat it as true? This is a classic JavaScript "falsy" trap. Because false is a falsy value, the logical OR operator (||) skips right over it and grabs your default value instead. The Fix: Use the Nullish Coalescing operator (??). It’s specifically designed to respect false and 0 while still providing a fallback for null or undefined. Check out the snippet below to see the difference! 👇 Have you made the switch to ?? yet, or do you still find yourself reaching for || ? Follow Wisdom Lamodot for more on #JavaScript #WebDevelopment #CodingTips #ReactJS
To view or add a comment, sign in
-
-
🚀 Async vs Normal Function in JavaScript (Quick Insight) The key difference is simple 👇 🔹 Normal function returns a value directly 🔹 Async function always returns a Promise Even if you return a normal string in an async function, JavaScript automatically wraps it inside a Promise. function normalFn() { return "Hello"; } async function asyncFn() { return "Hello"; } 👉 Behind the scenes: asyncFn(); // Promise { "Hello" } ✨ In short: Async functions *always* convert your return value into a Promise — even when you don’t explicitly use one. #JavaScript #AsyncAwait #WebDevelopment
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering
To view or add a comment, sign in
-
-
Most people don’t understand the JavaScript Event Loop. So let me explain it in the simplest way possible: JavaScript is single-threaded. It can only do ONE thing at a time. It uses something called a call stack → basically a queue of things to execute. Now here’s where it gets interesting: When async code appears (like promises or setTimeout), JavaScript does NOT execute it right away. It sends it away to the Event Loop and then keeps running what’s in the call stack. Only when the call stack is EMPTY… the Event Loop starts pushing async tasks back to be executed. Now look at the code in the image. What do you think runs first? Actual output: A D C B Why? Because not all async is equal: Promises (microtasks) → HIGH priority setTimeout (macrotasks) → LOW priority So the Event Loop basically says: “Call stack is empty? cool… let me run all promises first… then I handle setTimeout” If you get this, async JavaScript stops feeling random. #javascript #webdevelopment #frontend #reactjs #softwareengineering
To view or add a comment, sign in
-
-
Can you explain the JavaScript event loop? Not because the concept is hard, but because explaining it clearly is what actually matters. Here’s the simplest way to break it down: JavaScript runs in a single thread, using a call stack to execute code. 1. Synchronous code runs first → Functions are pushed to the call stack and executed immediately 2. Async tasks are handled by the browser/environment → e.g. setTimeout, fetch, DOM events 3. Once the call stack is empty → the event loop starts working It processes queues in this order: 👉 Microtasks first (Promises, queueMicrotask) 👉 Then macrotasks (setTimeout, setInterval, I/O) Why? - A and D are synchronous → executed first - Promise (C) → microtask queue → runs next - setTimeout (B) → macrotask → runs last Explaining it step by step is simple — but doing it clearly makes all the difference. #Frontend #JavaScript #WebDevelopment #TechInterviews #SoftwareEngineering
To view or add a comment, sign in
-
-
I've been writing JavaScript for over a year. Thought I understood var, let, and const. I didn't. "var a" inside a block accessible outside. Prints "10". "let b" inside the same block, try to access it outside and you get: ReferenceError: b is not defined Same block. Same code. Completely different behavior. Turns out var lives in global memory. let and const get their own separate block scope. Once the block is done, they're gone. This is why going back to fundamentals matters #JavaScript #WebDev #LearnInPublic #NamasteJavaScript
To view or add a comment, sign in
-
-
📣 𝗡𝗲𝘅𝘁 𝗕𝗹𝗼𝗴 𝗶𝘀 𝗛𝗲𝗿𝗲! ⤵️ Synchronous vs Asynchronous JavaScript ⚡🧠 One of the most important JavaScript concepts for understanding how code executes—explained in a simple and beginner-friendly way. 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/gqmv62WJ 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ What synchronous code means ⇢ What asynchronous behavior means ⇢ Blocking vs non-blocking code ⇢ Why JavaScript needs async behavior ⇢ Understanding setTimeout() execution ⇢ API calls and delayed responses ⇢ Simple execution timeline breakdown ⇢ What happens behind the scenes (task queue idea) ⇢ Common beginner confusion with execution order 💬 If you're learning JavaScript and have ever wondered why End logs before a timer finishes, this blog will help make it click. #ChaiAurCode #JavaScript #AsyncJavaScript #Synchronous #WebDevelopment #100DaysOfCoding
To view or add a comment, sign in
-
-
💡 Still confused about call(), apply(), and bind() in JavaScript? Let’s fix that in 60 seconds. If you've ever struggled with how this works in JavaScript… you're not alone. These three methods are your secret weapons to take control of it. 👉 Here’s the simplest way to understand them: 🔹 call() Invokes the function immediately Pass arguments one by one fn.call(thisArg, arg1, arg2) 🔹 apply() Also invokes immediately But takes arguments as an array fn.apply(thisArg, [args]) 🔹 bind() Does NOT run immediately Returns a new function you can call later const newFn = fn.bind(thisArg) 🧠 Think of it like this: call → “Run now, here are the args” apply → “Run now, here’s a list of args” bind → “Save this for later with this context” ✨ Why it matters: Mastering these helps you: ✔ Control this like a pro ✔ Reuse methods across objects ✔ Avoid common bugs in callbacks & event handlers 🔥 Pro tip: In modern JS, apply() is less common thanks to the spread operator: fn.call(thisArg, ...args) 📌 If you're preparing for interviews or leveling up your JS fundamentals — this trio is a must-know. 💬 Which one do you use the most: call, apply, or bind? #JavaScript #WebDevelopment #Frontend #CodingTips #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Why Does null Show as an Object in JavaScript? 🤯 While practicing JavaScript, I came across something interesting: let myVar = null; console.log(typeof myVar); // Output: object At first, it feels confusing… why is null an object? 🤔 💡 Here’s the simple explanation: null is actually a primitive value that represents "no value" or "empty". But when JavaScript was first created, there was a bug in the typeof operator. Due to this bug, typeof null returns "object" instead of "null". ⚠️ This behavior has been kept for backward compatibility, so changing it now would break existing code. 🔍 Key Takeaways: null → means "nothing" (intentional empty value) typeof null → returns "object" (this is a historical bug) Objects (like {}) also return "object" 💻 Example: let myObj = { name: "John" }; console.log(typeof null); // object ❌ (bug) console.log(typeof myObj); // object ✅ (correct) 📌 Conclusion: Even though both return "object", they are completely different in meaning. 👉 JavaScript is powerful, but it has some quirky behaviors—this is one of them! #JavaScript #WebDevelopment #CodingJourney #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
🚨 Ever wondered why your JavaScript code doesn’t freeze even when tasks take time? Here’s the secret: the event loop — the silent hero behind JavaScript’s non-blocking magic. JavaScript is single-threaded, but thanks to the event loop, it can handle multiple operations like a pro. Here’s the simplified flow: ➡️ The Call Stack executes functions (one at a time, LIFO) ➡️ Web APIs handle async tasks like timers, fetch, and DOM events ➡️ Completed tasks move to the Callback Queue (FIFO) ➡️ The Event Loop constantly checks and pushes callbacks back to the stack when it’s free 💡 Result? Smooth UI, responsive apps, and efficient async behavior — all without true multithreading. Understanding this isn’t just theory — it’s the difference between writing code that works and code that scales. 🔥 If you’re working with async JavaScript (Promises, async/await, APIs), mastering the event loop is a game-changer. #JavaScript #WebDevelopment #AsyncProgramming #EventLoop #Frontend #CodingTips
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