简体   繁体   中英

global variable returns undefined when used in a function

When I define the variable outside of a func, it returns undefined. I couldn't find out the reason why.

document.write(myFunc());

var x = 1;
function myFunc() {
    return x;
}

output: undefined

However if I define variable inside the func, it works.

document.write(myFunc());

function myFunc() {
    var x = 1;
    return x;
}

output: 1

You have fallen foul of a common misconception. Variable and function declarations are processed before any code is executed, however assignments occur in sequence in the code. So your code is effectively:

// Function declarations are processed first
function myFunc() {
    return x;
}

// Variable declarations are processed next and initialised to undefined
// if not previously declared
var x;

// Code is executed in sequence
document.write(myFunc());

// Assignment happens here (after calling myFunc)
x = 1;

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