🚀 The JavaScript “Gotcha” That Confuses Even Experienced Devs 😅 Let’s look at this classic head-scratcher 👇 var x = 1; function test() { console.log(x); // 🤔 What prints here? var x = 2; } test(); // Output? Most people expect 1, but the actual output is undefined ⚡ 💡 Why? When JavaScript executes this code, it doesn’t run top-to-bottom linearly. It first creates an execution context for test(). During that setup phase: The declaration var x inside test() is hoisted to the top. It’s initialized with the value undefined. This local x shadows the global one — even before assignment happens. So when console.log(x) runs, JS finds a local x (which is still undefined) and stops there. The global x = 1 is ignored completely. Now, let’s tweak one small line 👇 var x = 1; function test() { console.log(x); // No local var } test(); // ✅ Output → 1 Here, there’s no local declaration, so JS walks up the scope chain and uses the global x. 🧠 Key Takeaway In JavaScript: > “What matters is where a variable is declared, not where it’s called.” Hoisting + scope can easily cause unexpected undefined values — especially in legacy var code. ⚡ Pro Tip Prefer let or const — they’re block-scoped and avoid this trap entirely 👇 let x = 1; function test() { console.log(x); // ReferenceError ❌ (due to Temporal Dead Zone) let x = 2; } The TDZ ensures you don’t accidentally use variables before they’re initialized. 💬 Have you ever lost time debugging a “weird undefined”? Share your favorite JavaScript scope/hoisting gotcha below 👇 👉 Follow Rahul R Jain for daily deep dives into how JavaScript really works under the hood. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #AsyncJS #Hoisting #Scope #InterviewPreparation #TechEducation #LearnToCode #WebEngineer #CodeNewbie #RahulJain
Rahul R Jain’s Post
More Relevant Posts
-
💛 𝗗𝗮𝘆 𝟮 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀, 𝗦𝗰𝗼𝗽𝗲, 𝗮𝗻𝗱 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 Today, I revisited one of the most confusing yet powerful concepts in JavaScript — 𝗵𝗼𝗶𝘀𝘁𝗶𝗻𝗴 and 𝘀𝗰𝗼𝗽𝗶𝗻𝗴. 🧠 💡 𝗖𝗼𝗻𝗰𝗲𝗽𝘁: JavaScript moves all declarations to the top of their scope during compilation — this is known as hoisting. However, the behavior differs based on whether you use var, let, const, or functions. 💻 𝗖𝗼𝗱𝗲 𝗦𝗻𝗶𝗽𝗽𝗲𝘁: console.log(a); // undefined (hoisted) var a = 10; console.log(b); // ❌ ReferenceError (in TDZ) let b = 20; sayHello(); // ✅ Works — function declarations are hoisted function sayHello() { console.log("Hello from a hoisted function!"); } // ❌ Error: sayHi is not a function sayHi(); var sayHi = function () { console.log("Hi from function expression!"); }; 🧩 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻: 0. var is hoisted and initialized with undefined. 1. let and const are hoisted but stay uninitialized in the temporal dead zone (TDZ). 2. Function declarations are fully hoisted, so you can call them before defining. 3. Function expressions (especially when assigned to var) behave like variables — hoisted but not initialized. 📈 𝗦𝗰𝗼𝗽𝗲 𝗪𝗶𝘀𝗱𝗼𝗺: var → function scope let & const → block scope Functions → create their own local scope 🔥 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Understanding how JavaScript creates and executes contexts will help you debug faster and think more like the JS engine itself. #JavaScript #100DaysOfCode #Hoisting #Scope #Functions #FrontendDevelopment #LearningEveryday
To view or add a comment, sign in
-
“The Secret Behind JavaScript’s Magic — The Event Loop 🧠” When I first learned JavaScript, I used to wonder — how can it handle so many things at once even though it’s single-threaded? 🤔 The answer lies in one beautiful mechanism — The Event Loop. Here’s what actually happens behind the scenes 👇 1️⃣ JavaScript runs in a single thread — only one thing executes at a time. 2️⃣ But when something async happens (like setTimeout, fetch, or Promise), those tasks are offloaded to the browser APIs or Node.js APIs. 3️⃣ Once the main call stack is empty, the event loop takes pending callbacks from the task queue (or microtask queue) and pushes them back into the stack to execute. So while it looks like JavaScript is multitasking, it’s actually just scheduling smartly — never blocking the main thread. Example:- console.log("Start"); setTimeout(() => console.log("Inside Timeout"), 0); Promise.resolve().then(() => console.log("Inside Promise")); console.log("End"); Output:- Start End Inside Promise Inside Timeout Even though setTimeout was “0 ms”, Promises (microtasks) always run before timeouts (macrotasks). That’s the secret sauce 🧠💫 Understanding this single concept can help you debug async behavior like a pro. #JavaScript #EventLoop #Async #WebDevelopment #Coding
To view or add a comment, sign in
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
*5 Things I Wish I Knew When Starting JavaScript 👨💻* Looking back, JavaScript was both exciting and confusing when I started. Here are 5 things I wish someone had told me earlier: *1. var is dangerous. Use "let" and "const" "var" is function-scoped and can lead to unexpected bugs. "let" and "const" are block-scoped and safer. *2. JavaScript is asynchronous Things like "setTimeout()"and "fetch()" don’t behave in a straight top-down flow. Understanding the *event loop* helps a lot. *3. Functions are first-class citizens* – You can pass functions as arguments, return them, and even store them in variables. It’s powerful once you get used to it. *4. The DOM is slow – avoid unnecessary access* – Repeated DOM queries and manipulations can hurt performance. Use "documentFragment" or batch changes when possible. *5. Don’t ignore array methods* map(), "filter()" , "reduce()", "find()"… they make code cleaner and more readable. I wish I started using them sooner. 💡 *Bonus Tip:* "console.log()" is your best friend during debugging! If you’re starting out with JS, save this. And if you're ahead in the journey — what do *you* wish you knew earlier? #JavaScript #WebDevelopment #CodingJourney #Frontend #LearnToCode #DeveloperTips
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop Have you ever wondered how JavaScript — a single-threaded language — handles async tasks like setTimeout(), fetch(), or Promises without freezing the browser? 🤔 That’s where the Event Loop comes in! 🌀 ⚙️ How it works 1️⃣ Call Stack → Executes synchronous code (like console.log()). 2️⃣ Web APIs → Handle async tasks (like timers or network requests). 3️⃣ Callback Queues Microtask Queue → Handles Promises and async/await. Macrotask Queue → Handles setTimeout, setInterval, etc. 4️⃣ Event Loop → Continuously checks: > “Is the call stack empty?” If yes → It pushes queued callbacks back to the stack for execution. 🧠 Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Because ➡️ A & D → run first (synchronous). C → from Promise (microtask). B → from setTimeout (macrotask). 💡 Takeaway > Event Loop makes JavaScript feel asynchronous — even though it runs on a single thread! ⚡ 🔖 #JavaScript #EventLoop #WebDevelopment #AsyncJS #Frontend #Angular #React #CodingTips
To view or add a comment, sign in
-
So, I was debugging my code (as usual 😭) and suddenly realized… JavaScript is single-threaded, but somehow it multitasks better than me! Like how?? 🤯 Turns out, the real hero behind the scenes is something called the Event Loop 🌀 Let me explain it my way 👇 🧠 JavaScript has only one main thread (the call stack). But when you throw async things at it like setTimeout, fetch, or promises, it says: “Bro, I’ll do it… but not right now 😌” So it sends that task to some background worker (Web APIs), continues with the main work, and once it’s done, the Event Loop checks- “Hey Stack, you free now? Can I bring in that callback?” That’s how JS looks multitasking while still being single-threaded. Smart, right? 😎 Quick demo: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even with 0ms delay, the async code waits politely for the main work to finish. 😂 So next time your async code behaves weirdly, don’t panic — just remember, it’s not broken, it’s just looping! 🔁 #JavaScript #WebDevelopment #EventLoop #AsyncJS #CodingFun #DevelopersLife
To view or add a comment, sign in
-
-
*5 Things I Wish I Knew When Starting JavaScript 👨💻* Looking back, JavaScript was both exciting and confusing when I started. Here are 5 things I wish someone had told me earlier: *1. `var` is dangerous. Use `let` and `const`* – `var` is function-scoped and can lead to unexpected bugs. `let` and `const` are block-scoped and safer. *2. JavaScript is asynchronous* – Things like `setTimeout()` and `fetch()` don’t behave in a straight top-down flow. Understanding the *event loop* helps a lot. *3. Functions are first-class citizens* – You can pass functions as arguments, return them, and even store them in variables. It’s powerful once you get used to it. *4. The DOM is slow – avoid unnecessary access* – Repeated DOM queries and manipulations can hurt performance. Use `documentFragment` or batch changes when possible. *5. Don’t ignore array methods* – `map()`, `filter()`, `reduce()`, `find()`… they make code cleaner and more readable. I wish I started using them sooner. 💡 *Bonus Tip:* `console.log()` is your best friend during debugging! If you’re starting out with JS, save this. And if you're ahead in the journey — what do *you* wish you knew earlier? #JavaScript #WebDevelopment #CodingJourney #Frontend #LearnToCode #DeveloperTips
To view or add a comment, sign in
-
How JS Converts [] + {} to [object Object] —🤯 JavaScript can be weirdly magical sometimes. Ever tried this in your console? 👇 [] + {} // Output: "[object Object]" At first glance, it looks confusing — why does an empty array and an empty object become a string? Let’s decode the magic 🪄 1️⃣ + Operator in JS The + operator doesn’t just add numbers — it can also concatenate strings. 2️⃣ Type Conversion Happens! [] (empty array) → when converted to string becomes "" (empty string). {} (empty object) → when converted to string becomes "[object Object]". 3️⃣ Final Expression So JS actually does: "" + "[object Object]" → "[object Object]" ✅ Bonus twist: Try reversing it: {} + [] Now it gives 0 because {} is treated as an empty block,not an object. 🤯 JavaScript — where logic meets magic ✨ 🔹 Follow Prashansa Sinha for more fun JS mysteries and simple explanations 👩💻 #JavaScript #WebDevelopment #Coding #Frontend #JS #LearnToCode #Programming #TechCommunity #Developers #CodeNewbie #WebDev
To view or add a comment, sign in
-
🚀 JavaScript Hoisting Explained (Simply!) Hoisting means JavaScript moves all variable and function declarations to the top of their scope before code execution. If that definition sounds confusing, see this example 👇 console.log(a); var a = 5; Internally, JavaScript actually does this 👇 var a; // declaration is hoisted (moved up) console.log(a); a = 5; // initialization stays in place ✅ Output: undefined --- 🧠 In Short: > Hoisting = JS reads your code twice: 1️⃣ First, to register variables & functions 2️⃣ Then, to execute the code line by line --- 💡 Tip: var → hoisted & initialized as undefined let / const → hoisted but not initialized (stay in Temporal Dead Zone) --- #JavaScript #Hoisting #WebDevelopment #CodingTips #JSInterview #Frontend #React #100DaysOfCode
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