0

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

1
  • 3
    You are calling myFunc before the value has been assigned to x. Commented Mar 11, 2016 at 1:26

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your response. However, It makes too complicated to assign a value to x = 1 at the end of execution. Wouldn't it be better to assign it when defining the value?
@BehramBeldagli—yes, of course, I'm just showing the effect of processing your code. If you want it to work, then put the initialiser for x at the top so the assignment happens first (or at least before myFunc is called).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.