2

Since in JavaScript functions are same as objects, they should have a similar scope in terms of where they are defined. However, the following code confuses me:

console.log(lateFunc());

function lateFunc(){
    return 'This function comes late!';
};

console.log(lateVar);

var lateVar = 'This variable comes late!';

In this case, lateFunc and lateVar are both define AFTER console command. However, this is what I got from node test.js:

This function comes late!
undefined

The first console recognizes the function that is defined later. However, the second one does not recognize the variable defined later. So I'm confused about why this is happening. Shouldn't they both have global scope OR visible only after definition? Can anyone explain?

4
  • 1
    The variable isn't defined later, it is assigned later. Think of it as definitions being processed before any code is actually run. Commented Feb 2, 2014 at 4:49
  • 2
    i think it is very clearly written here, stackoverflow.com/questions/3887408/…... hv fun Commented Feb 2, 2014 at 4:50
  • You also got an answer here: stackoverflow.com/questions/261599/… Commented Feb 2, 2014 at 4:53
  • Defining 'before' or 'after' is for variables and not functions. Commented Feb 2, 2014 at 4:58

2 Answers 2

2

In JavaScript, this code...

console.log(lateVar);
var lateVar = 'This variable comes late!';

is actually equivalent to...

var lateVar = undefined;
console.log(lateVar);
lateVar = 'This variable comes late!';

which explains why this is happening. A function defined like this...

function lateFunc(){
    return 'This function comes late!';
};

is different and is defined in the whole scope.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

It's due to the compilation vs expression nature of javascript language.

function fun1() is declared, so it exists since compile state.

var fun1 = 'sth sth'; is an assignment expression, so it depends on the execution order.

Source

JavaScript function declaration and evaluation order

Comments

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.