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?

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • 1
    The variable isn't defined later, it is *assigned* later. Think of it as definitions being processed before any code is actually run. – Matt Way Feb 02 '14 at 04:49
  • 2
    i think it is very clearly written here, http://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order... hv fun – clouddreams Feb 02 '14 at 04:50
  • You also got an answer here: http://stackoverflow.com/questions/261599/why-can-i-use-a-function-before-its-defined-in-javascript – zipp Feb 02 '14 at 04:53
  • Defining 'before' or 'after' is for variables and not functions. – Mostafa Shahverdy Feb 02 '14 at 04:58

2 Answers2

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.

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
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

Community
  • 1
  • 1
clouddreams
  • 622
  • 1
  • 4
  • 13