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
Jackson Kasi -
Mekzy -
Jackson Kasi -
Amy Liu -
Once suspended, yashwanth2804 will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, yashwanth2804 will be able to comment and publish posts again.
Once unpublished, all posts by yashwanth2804 will become hidden and only accessible to themselves.
If yashwanth2804 is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to kambala yashwanth.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community safe. Here is what you can do to flag yashwanth2804:
Unflagging yashwanth2804 will restore default visibility to their posts.
Latest comments (3)
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.
Currently, your
a
variable lives inside of the function #f and is out of scope once not called within the #f function.There are two possible solutions to your problem:
a
variable value and assign that value to yourlet a
variable.a
and assign the value to that reference.Note: #f has been written down as a reference to Lambda, this is nothing more than a representation for the function
f()
in an undefined class.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