The output says 5, but it isn't. Please help! :(

aNumber is not undefined but 10 is the output. What’s wrong with my code?
Please check my code:

var aNumber = 5;
function changeValue() {
    if (aNumber === undefined) {
        var aNumber = 10;
    }
    console.log(aNumber);
}
changeValue();

Can you please help @Grasshopper_Ben?

Thanks!
D :slight_smile:

1 Like

Hello, In if statements you should type aNumber=10 only
But you used var keyword and updated aNumber assigning to value 10
Thank you

2 Likes

To expand a little further on @Codeinventor’s explanation, when you used the var keyword inside the function, you created a new variable also called aNumber, but this one limited in scope to just that function.

The new aNumber variable is not acessible outside of the function, and despite having the same name as the first one, they are stored differently. so changing one doesn’t affect the other.

And since JS is not whitespace dependant, even though the console.log is at the same level as the function, it is outside the braces, so it can only access the first aNumber, which is 5. Hope that helps.

:clap: :clap: :smile_cat:

3 Likes
1 Like