JavaScript Hoisting: Understanding Variable and Function Behavior

𝗗𝗮𝘆 𝟱/𝟵𝟬: 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 — 𝗧𝗵𝗲 "𝗜𝗻𝘃𝗶𝘀𝗶𝗯𝗹𝗲" 𝗟𝗶𝗳𝘁 I learned that JavaScript doesn’t always run top-to-bottom. It has a unique behavior called 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴, where declarations are moved to the top of the scope before execution. Here is the "Cheat Sheet" for how JS handles different types: 🔹 𝘃𝗮𝗿 (𝗧𝗵𝗲 𝗟𝗼𝗼𝘀𝗲 𝗪𝗮𝘆): Hoisted but initialized as undefined. You can use it before the code line, but you won't get the value. 🔹 𝗹𝗲𝘁 & 𝗰𝗼𝗻𝘀𝘁 (𝗧𝗵𝗲 𝗠𝗼𝗱𝗲𝗿𝗻 𝗪𝗮𝘆): Hoisted but stuck in the 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭). Accessing them early triggers a ReferenceError. 🔹 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 (𝗧𝗵𝗲 𝗩𝗜𝗣𝘀): Fully hoisted. You can call a function at the top of your script even if it’s defined at the very bottom! 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Just because you can use hoisting doesn't mean you should. Professional code always declares variables first to keep logic clear and bug-free. Understanding these "quirks" is what separates a coder from an Engineer. 👨💻 #90DaysOfCode #JavaScript #PentagonSpace #FullStack #WebDev #Hoisting #CleanCode

To view or add a comment, sign in

Explore content categories