💡 JavaScript Surprise: await works on NON-promises?! const obj = { then: () => console.log("I'm evil 😈") }; await obj; // I'm evil 😈 At first glance, this looks strange… Why is await calling then() on a plain object? 👉 The answer lies in a powerful (and sometimes dangerous) concept: Thenables 🚀 What’s happening here? In JavaScript, await doesn’t just wait for Promises. It follows the "thenable protocol": If an object has a .then() method… JavaScript treats it like a Promise! So internally, this: await obj; Becomes something like: Promise.resolve(obj).then(...) And since your object has a then() method, it gets executed automatically. ⚠️ Why this matters This behavior can: Lead to unexpected side effects Introduce hard-to-debug issues Even be abused in malicious patterns 😈 🧠 Key takeaway “In JavaScript, anything with a .then() can act like a Promise.” So always be careful when: Working with external data Designing APIs Overloading object behavior 🔥 Pro tip Avoid adding a .then() method to objects unless you intentionally want them to behave like Promises. JavaScript is flexible… sometimes too flexible 😅 #JavaScript #AsyncAwait #WebDevelopment #Programming #100DaysOfCode #JSDeepDive #reactjs #nodejs
JavaScript Await on Non-Promises: The Thenable Protocol
More Relevant Posts
-
🚀 JavaScript Output Prediction Challenge What will be the output? 🤔 💡 Important Behaviour: 👉 JavaScript executes code line by line 👉 The very first line throws the following: ❌ ReferenceError: a is not defined So in reality, the programme stops immediately and nothing else runs. 📌 Now, let’s understand what would happen inside the function (ignoring the first error): 👉 Before execution, JS does Hoisting (memory creation phase) Inside the function: var a → hoisted and initialized as undefined let b → hoisted but kept in Temporal Dead Zone (TDZ) (not accessible yet) 👉 Execution phase: "1:" → undefined (Because 'a' exists but not assigned yet) "2:" → ❌ ReferenceError (because b is in TDZ) After assignment: a = 10 b = 20 "3:" → 10 "4:" → 20 🔥 Core Concepts: JS has 2 phases → Memory Creation + execution. var → hoisted + usable as undefined let/const → hoisted but blocked by TDZ 💬 If you got this right, your JS fundamentals are solid 👇 #JavaScript #Hoisting #Frontend #CodingChallenge #WebDevelopment
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting — what it actually means (with a simple mental model) Most people say: “Variables and functions are moved to the top". Even the educators on youtube (some of them) are teaching that and even I remember answering that in my first interview call. That’s not wrong… but it’s also not the full picture. Then Priya what’s really happening? JavaScript doesn’t “move” your code. Instead, during execution, it runs in two phases: 1️⃣ Creation Phase Memory is allocated Variables → initialised as undefined Functions → fully stored in memory 2️⃣ Execution Phase Code runs line by line Values are assigned 🎨 Think of it like this: Before running your code, JavaScript prepares a “memory box” 📦 Creation Phase: a → undefined sayHi → function() { ... } Execution Phase: console.log(a) → undefined a = 10 🔍 Example 1 (var) console.log(a); // undefined var a = 10; 👉 Why? Because JS already did: var a = undefined; ⚡ Example 2 (function) sayHi(); // Works! function sayHi() { console.log("Hello"); } 👉 Functions are fully hoisted with their definition. 🚫 Example 3 (let / const) console.log(a); // ❌ ReferenceError let a = 10; 👉 They are hoisted too… But stuck in the Temporal Dead Zone (TDZ) until initialised. 🧩 Simple rule to remember: var → hoisted + undefined function → hoisted completely let/const → hoisted but unusable before declaration 💬 Ever seen undefined and wondered why? 👉 That’s hoisting working behind the scenes. #javascript #webdevelopment #frontend #reactjs #programming #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
**AVOID JAVASCRIPT'S QUIET BUGS:** **Don't use ==, use ===** --- 🔺 **THE PROBLEM: == COERCION** ```js console.log([] == false); // prints true! 😅 ``` **The behind-the-scenes journey:** ``` [] ↓ (empty array) "" ↓ (string) 0 ↓ (number) false ↓ (boolean) 0 ``` Wait, why is that true? JavaScript silently converts types, leading to unexpected results. **This is confusing behavior!** --- 🔺 **THE FIX: STRICT EQUALITY** ```js console.log([] === false); // prints false! 🎉 ``` Uses strict comparison without hidden type conversions. **Predictable and safe.** --- 🔺 **NO HIDDEN CONVERSION!** --- **MAKING YOUR CODE PREDICTABLE: ALWAYS USE ===** Have you encountered confusing JavaScript type coercion? Share your experience! 👇 #javascript #webdevelopment #frontend #coding #developers #mern #learning
To view or add a comment, sign in
-
-
Day 3: Hoisting — The JavaScript "Magic" That Isn't Magic at All! 🎩✨ Today, I tackled one of the most famous (and often misunderstood) concepts in JavaScript: Hoisting. If you've ever wondered why you can call a function before you even define it in your code, you've witnessed Hoisting in action! 🤔 What is Hoisting? Hoisting is a mechanism where variables and function declarations are moved to the top of their containing scope during the Memory Allocation Phase, before the code even starts executing. 🔍 Under the Hood (The Execution Context) Remember the "Big Box" (Execution Context) from Day 1? Here is what happens during the Memory Phase: Variables (var): JS allocates memory for variables and initializes them with a special value: undefined. Functions: JS stores the entire function body in memory. This is why: Calling a function at Line 1 works perfectly! ✅ Accessing a var at Line 1 returns undefined instead of an error! ⚠️ 💻 The Browser Demo (The Call Stack) Watching this live in the Sources tab of Chrome DevTools was a game-changer. Seeing the Global scope populate with variables before the first line of code executed made everything click. 💡 Interview Tip: When asked "What is Hoisting?", don't just say "it moves code to the top." Better Answer: "Hoisting is the process where the JS Engine allocates memory for variables and functions during the Creation Phase of the Execution Context. This allows us to access functions and variables even before they are initialized in the code, though var will return undefined until the execution reaches its assignment." Next up: Diving into how let and const handle hoisting differently (The Temporal Dead Zone!). Are you a var, let, or const person? Let's discuss below! 👇 #JavaScript #WebDevelopment #Hoisting #NamasteJavaScript #CodingInterviews #FrontendEngineer #ProgrammingLogic #JSFundamentals
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Hoisting) You write this: console.log(a); var a = 10; You expect: 👉 ReferenceError But you get: 👉 undefined 🤯 Now try this: console.log(b); let b = 20; 👉 This time you get: ReferenceError ❌ Same with: console.log(c); const c = 30; 👉 Error again ❌ Now look at functions 👇 sayHi(); function sayHi() { console.log("Hello"); } 👉 This works ✅ But this doesn’t: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Why different behavior? This happens because of Hoisting 📌 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 📌 What’s actually happening? ✔ var: var a; console.log(a); // undefined a = 10; 👉 Hoisted + initialized ✔ let / const: 👉 Hoisted but NOT initialized 👉 Access before declaration → ReferenceError 👉 (Temporal Dead Zone) ✔ Function declarations: function sayHi() {} 👉 Fully hoisted (can be called before definition) ✔ Function expressions: const sayHello = function () {} 👉 Behave like variables 👉 Not usable before declaration 💡 Takeaway: ✔ var → hoisted + initialized ✔ let / const → hoisted but restricted (TDZ) ✔ Function declarations → fully hoisted ✔ Function expressions → NOT hoisted like functions 👉 Same concept… different rules 🔁 Save this before hoisting confuses you again 💬 Comment “hoisting” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🧠 JavaScript Scope & Lexical Scope Explained Simply Many JavaScript concepts like closures, hoisting, and this become much easier once you understand scope. Here’s a simple way to think about it 👇 🔹 What is Scope? Scope determines where variables are accessible in your code. There are mainly 3 types: • Global Scope • Function Scope • Block Scope (let, const) 🔹 Example let globalVar = "I am global"; function test() { let localVar = "I am local"; console.log(globalVar); // accessible } console.log(localVar); // ❌ error 🔹 What is Lexical Scope? Lexical scope means that scope is determined by where variables are written in the code, not how functions are called. Example 👇 function outer() { let name = "Frontend Dev"; function inner() { console.log(name); } inner(); } inner() can access name because it is defined inside outer(). 🔹 Why this matters Understanding scope helps you: ✅ avoid bugs ✅ understand closures ✅ write predictable code 💡 One thing I’ve learned: Most “confusing” JavaScript behavior becomes clear when you understand how scope works. Curious to hear from other developers 👇 Which JavaScript concept clicked for you only after learning scope? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🚀 JavaScript String Optimization You Probably Didn’t Know When you build strings in a loop like this: let bigString = ""; for (let i = 0; i < 1000; i++) { bigString += "chunk" + i; } It looks expensive… but surprisingly, it’s not (at first). 👉 JavaScript engines are smart. Instead of immediately creating a new string every time, they use something called a ConsString (concatenated string) — a lazy structure that avoids copying data. ⚡ This means: String building stays fast and memory-efficient No actual concatenation happens yet But here’s the catch… 💥 The moment you try to access the string (like bigString[0]), JavaScript materializes it — flattening everything into a real string, which can be expensive. 📌 Key Insight: Building strings → cheap Accessing/manipulating them → can trigger hidden cost 💡 Takeaway: Performance isn’t just about what you write — it’s about when the engine does the heavy work. #JavaScript #WebPerformance #CleanCode #Programming #FrontendDevelopment #DevTips #reactjs #webdevelopment
To view or add a comment, sign in
-
-
Ever faced a moment in JavaScript where something just didn’t make sense? 😅 I was debugging a small issue and saw this: 1 + "2" → "12" "5" - 2 → 3 [] == ![] → true At first, I thought I messed up somewhere… but nope — it was type coercion doing its thing. Basically, JavaScript tries to be “helpful” by converting values automatically. Sometimes it helps… sometimes it confuses you even more. Here are a few examples I explored 👇 • 1 + "2" → "12" (number becomes string) • "10" - 5 → 5 (string becomes number) • true + 1 → 2 • false + 1 → 1 • null + 1 → 1 • undefined + 1 → NaN • [] + [] → "" • [] + {} → "[object Object]" • {} + [] → 0 (weird one 👀) • [] == false → true • "0" == false → true • null == undefined → true • null === undefined → false What I learned from this 👇 → If there’s a string, + usually concatenates → Other operators (-, *, /) convert to number → == can trick you, === is safer Now whenever I see weird JS behavior… my first thought is: “Is type coercion involved?” 😄 #javascript #webdevelopment #coding #frontend #learning
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