Behram
Behram

Reputation: 1

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

Upvotes: 0

Views: 53

Answers (1)

RobG
RobG

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

Related Questions