function f(){
let a=1;
}
let a;
f();
console.log(a);
why output is undefined
function f(){
let a=1;
}
let a;
f();
console.log(a);
why output is undefined
For further actions, you may consider blocking this person and/or reporting abuse
Digvijay Bhakuni -
Aditya Pratap Bhuyan -
Aditya Pratap Bhuyan -
Vinicius Porto -
Top comments (2)
I know I'm a little late to the party, but for anyone else who stumbles across this thread:
What's happening here is known as variable shadowing - This is a special case of variable scope where a variable in a sub-scope uses the same name as a variable in a higher scope (usually making the higher-scoped variable inaccessible)
To explain why this happens: the
let
,const
, andvar
keywords in JavaScript always attempt to create a new variable, but only check for name collisions in the current scope - if you reuse a name from a higher scope, JavaScript will add a new variable to your current scope, and happily call it a day.Here are some examples of how this works
And here are a couple instances where it doesn't work
Just a note: There's nothing wrong with variable shadowing - it's a super useful tool for reusing variable names without worrying about affecting other variables. Just be sure you know you're doing it, and be sure to check for it whenever you're modifying a variable from a parent scope.
Because a is undefined.
The first a is scoped inside a function. You're printing the a that's outside and undefined.
So, a inside f lives inside the f, but it has nothing to do with the other a, they just share the same name