So if I declared a variable using `let`/`const` outside of a block where can I access it?


#1

Question

So if I declared a variable using let/const outside of a block where can I access it?

Answer

You’d be able to access your variable anywhere else below where you declared it so long as you don’t leave outside the scope you’re in. What that means is if you have blocks inside the current block of your variable, that’s fine. You variable is still accessible. But, say your variable is declared inside of a block, it can still be accessed in that block and blocks within your block, but wouldn’t be accessible outside of the block it’s defined. Example:
javascript let x = 2; const myFunc = () { let y = 3; // This is fine because we're in the same scope as y console.log(x + y); const innerFunc = () { let z = 4; // This works because z is defined in this scope and y is defined in an outer scope console.log(x + y + z); } // Will return an error because y isn't defined for this scope, it's defined in an inner scope which our code here doesn't have access to. console.log(x + y + z); }; // Will return an error because y isn't defined for this scope console.log(x + y);