Reputation: 1
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;
}
However if I define variable inside the func, it works.
document.write(myFunc());
function myFunc() {
var x = 1;
return x;
}
Upvotes: 0
Views: 53
Reputation: 147503
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;
Upvotes: 1