JavaScript Block Scope and Variable Hoisting Explained

𝐀𝐭 𝐟𝐢𝐫𝐬𝐭, { } 𝐥𝐨𝐨𝐤𝐞𝐝 𝐥𝐢𝐤𝐞 𝐣𝐮𝐬𝐭 𝐬𝐲𝐧𝐭𝐚𝐱. Then I realized it actually defines 𝐡𝐨𝐰 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐜𝐨𝐧𝐭𝐫𝐨𝐥𝐬 𝐚𝐜𝐜𝐞𝐬𝐬. The confusion started when variables behaved differently inside and outside blocks. Some were accessible, some weren’t — even though they were declared only a few lines apart. That’s when 𝐛𝐥𝐨𝐜𝐤 𝐬𝐜𝐨𝐩𝐞 and 𝐬𝐡𝐚𝐝𝐨𝐰𝐢𝐧𝐠 started to make sense. In JavaScript, a 𝐛𝐥𝐨𝐜𝐤 (also called a 𝐜𝐨𝐦𝐩𝐨𝐮𝐧𝐝 𝐬𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭) is a group of statements wrapped in { }. Blocks exist so multiple statements can be used where JavaScript expects a single one — like in if, for, or while. This grouping directly affects scope. What clarified it for me: A 𝐛𝐥𝐨𝐜𝐤 𝐬𝐜𝐨𝐩𝐞 allows access only within its { }. let and const are 𝐡𝐨𝐢𝐬𝐭𝐞𝐝 𝐢𝐧𝐬𝐢𝐝𝐞 𝐭𝐡𝐞 𝐛𝐥𝐨𝐜𝐤 𝐬𝐜𝐨𝐩𝐞. They get 𝐬𝐞𝐩𝐚𝐫𝐚𝐭𝐞 𝐦𝐞𝐦𝐨𝐫𝐲 𝐬𝐩𝐚𝐜𝐞 limited to that block. var is hoisted to the 𝐠𝐥𝐨𝐛𝐚𝐥 (𝐨𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧) 𝐬𝐜𝐨𝐩𝐞. After the block ends, let and const are inaccessible, but var is not. 𝐒𝐡𝐚𝐝𝐨𝐰𝐢𝐧𝐠 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐰𝐡𝐞𝐧 𝐚 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞 𝐢𝐧𝐬𝐢𝐝𝐞 𝐚 𝐛𝐥𝐨𝐜𝐤 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐞𝐬 𝐚 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐬𝐚𝐦𝐞 𝐧𝐚𝐦𝐞 𝐨𝐮𝐭𝐬𝐢𝐝𝐞 𝐢𝐭. With let and const, this is intentional and scoped. With var, things get risky. 𝐈𝐥𝐥𝐞𝐠𝐚𝐥 𝐬𝐡𝐚𝐝𝐨𝐰𝐢𝐧𝐠 occurs when a let variable is shadowed by var, because var ignores block boundaries. What changed my thinking is realizing that block scope still follows 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐬𝐜𝐨𝐩𝐢𝐧𝐠 . Scopes are determined by where the code is written — not how it runs. Once that clicks, shadowing stops being mysterious and starts being predictable. #JavaScript #SoftwareEngineering #ProblemSolving #DeveloperJourney #LearningInPublic #TechCommunity #ContinuousLearning

  • graphical user interface

To view or add a comment, sign in

Explore content categories