DEV Community

kambala yashwanth
kambala yashwanth

Posted on

 

Let re initialized and declaring

function f(){

 let a=1;
}
let a;
f();
console.log(a);

why output is undefined

Oldest comments (3)

Collapse
 
rhymes profile image
rhymes • Edited

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

Collapse
 
remcobuddelmeijer profile image
Remco Buddelmeijer

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:

  1. Make function #f return your a variable value and assign that value to your let a variable.
  2. Make a reference to 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.

Collapse
 
canderson93 profile image
Carl Anderson • Edited

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, and var 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

function f () {
    let a = 0;
    console.log(a); //prints 0
}
let a = 1;
f();
console.log(a) // prints 1
var a = 0;
if (a === 0) {
    let a = 1; //totally fine, because `a` is scoped to the 'if' block
    console.log(a); //prints 1
}
console.log(a); //prints 0

And here are a couple instances where it doesn't work

function f () {
    a = 0; // no let or var keyword, so references `a` in the parent scope
    console.log(a); //prints 0
}
let a = 1;
f();
console.log(a) // prints 0
let a = 0;
if (a === 0) {
    var a = 0; // `var` isn't scoped to the if block, so it collides with the other a, and we get a SyntaxError
    console.log(a)
}
console.log(a);

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.