简体   繁体   中英

console.log() not working as expected

Question: What would be consoled

var foo = 'outside';

function logIt() {
    console.log(foo);
    var foo = 'inside';
}

logIt();

Answer: undefined

Can someone explain why this is happening.

var statements are hoisted.

There is only one variable accessed inside the function: The one created on the line var foo = 'inside'; .

When you log the value of it, you do so before the assignment has taken place, so it is undefined .

You can't access the global variable of the same name from within the function because you have masked it by declaring a locally scoped variable of the same name.

var foo = 'outside';

function logIt() {
    var foo;
    console.log(foo);
    foo = 'inside';
}

logIt();

This is how the script is interpreted.So it gives undefined

This is called top-hoisting .

In this way re-declaration of foo is occur which set it to undefined

var foo = 'outside';

function logIt() {
    console.log(window.foo);
    var foo = 'inside';
}
logIt();

logIt function assumes that foo is inside its scope. To use global variable you need to use window.variable_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM