🔍 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
Avinash Verma’s Post
More Relevant Posts
-
🔍 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 Behavior You Might Have Seen (Array methods: mutate vs not) You write this: const arr = [1, 2, 3]; const newArr = arr.push(4); console.log(arr); // ? console.log(newArr); // ? You expect: 👉 newArr to be a new array But you get: 👉 arr → [1, 2, 3, 4] 👉 newArr → 4 This happens because of mutating array methods 📌 What does “mutate” mean? 👉 It means changing the original array In this case: 👉 push() modifies arr directly 👉 And returns the new length (not a new array) Now look at this 👇 const arr = [1, 2, 3]; const newArr = arr.map(x => x * 2); console.log(arr); // ? console.log(newArr); // ? 👉 arr → [1, 2, 3] 👉 newArr → [2, 4, 6] This is a non-mutating method 👉 It creates a new array 👉 Original array stays unchanged 📌 Common mutating methods: ✔ push ✔ pop ✔ shift ✔ unshift ✔ splice ✔ sort ✔ reverse 📌 Common non-mutating methods: ✔ map ✔ filter ✔ slice ✔ concat ✔ reduce 📌 Real problem: You think you’re creating a new array… 👉 But you accidentally modify the original one 💡 Takeaway: ✔ Mutating methods change original array ✔ Non-mutating methods return a new array ✔ Always be careful when updating state (especially in React) 👉 One wrong method can break your logic silently 🔁 Save this for later 💬 Comment “array” 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 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 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
-
-
🔍 JavaScript Bug You Might Have Seen (setTimeout vs Promise) You write this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you expect? Start Timeout Promise End But actual output is: Start End Promise Timeout This happens because of the Event Loop 📌 What is the Event Loop? 👉 The event loop is the mechanism that decides which task runs next in JavaScript’s asynchronous execution. 📌 Priority order (very important): 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue 3️⃣ Macrotask Queue 📌 What’s inside each queue? 👉 Microtask Queue (HIGH priority): ✔ Promise.then / catch / finally ✔ queueMicrotask ✔ MutationObserver 👉 Macrotask Queue (LOWER priority): ✔ setTimeout ✔ setInterval ✔ setImmediate ✔ I/O tasks ✔ UI rendering events Execution flow: ✔ Step 1: Run all synchronous code 👉 Start → End ✔ Step 2: Execute ALL microtasks 👉 Promise ✔ Step 3: Execute macrotasks 👉 setTimeout So final order becomes: Start End Promise Timeout 💡 Takeaway: ✔ Microtasks run before macrotasks ✔ Promises > setTimeout ✔ setTimeout(fn, 0) is NOT immediate 👉 Understand queues = master async JS 🔁 Save this for later 💬 Comment “event loop” 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 Behavior You Might Have Seen (Prototype Chain) You write this: const arr = [1, 2, 3]; console.log(arr.toString()); // ? 👉 Did you define toString on this array? 👉 Did you even define it anywhere? No. Still it works. Now think step by step 👇 When you do: 👉 arr.toString JavaScript checks: Inside arr → ❌ not found Inside Array.prototype → ❌ not found Inside Object.prototype → ✔ found This step-by-step lookup is called the Prototype Chain 📌 What is Prototype Chain? 👉 It’s the process JavaScript uses to find a property by searching up through prototypes. 📌 How it works? Every object is linked to another object (its prototype) So lookup happens like this: 👉 arr → Array.prototype → Object.prototype → null Same with strings 👇 const str = "hello"; console.log(str.hasOwnProperty("length")); // ? 👉 hasOwnProperty is not in string JS finds it here: 👉 str → String.prototype → Object.prototype 📌 Important point: 👉 JavaScript keeps searching until it finds the property or reaches null 💡 Takeaway: ✔ Prototype Chain = lookup mechanism ✔ JS searches step by step ✔ That’s how all built-in methods work 👉 If you understand this, you’ll understand how JavaScript really works 💬 Comment “chain” if this clicked 🔁 Save this for later ❤️ Like for more JavaScript deep dives #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
-
🚀 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 Bug You Might Have Seen (null vs undefined) You write this: let a; console.log(a); // ? let b = null; console.log(b); // ? Both look similar… But they are NOT the same. 💥 Output: undefined null Now here’s where it gets confusing 👇 console.log(null == undefined); // ? console.log(null === undefined); // ? 💥 Output: true false Wait… WHAT? 🤯 This happens because of how JavaScript treats them. 📌 What is undefined? 👉 A variable that is declared but NOT assigned a value 📌 What is null? 👉 A value that represents “intentional absence of value” (You explicitly set it) 📌 Then why this? null == undefined // true Because == does loose comparison 👉 It treats them as equal BUT: null === undefined // false Because === checks: ✔ Value ✔ Type 💡 Takeaway: ✔ undefined → JS gives it ✔ null → YOU assign it ✔ == → treats them equal ✔ === → they are different 👉 Use undefined for default/unassigned 👉 Use null when you intentionally want “no value” 🔁 Save this before it confuses you again 💬 Comment “null” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
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