1

I encountered a problem that I can not seem to understand, why if define tick function like this;

function tick () { /* do something */ }

It works fine and in this mode

var tick = function () { /* do something */ }

doesn't work. Where is the problem?

working example of first http://jsbin.com/omokap/10/edit

working example of second http://jsbin.com/isobul/1/edit

Scorpy86
  • 339
  • 1
  • 3
  • 16
  • you misspelled "function" probably :) – Gintas K Jul 18 '13 at 08:57
  • There is a typo. `fucntion` should be `function`. If that's not the problem, then you are trying to use the function before it was defined. But to properly help you, you have to post the relevant part of your code. – Felix Kling Jul 18 '13 at 08:57
  • @GintasK `fucntion` is a typing error :D @FelixKling, i've added 2 example, please check if d3js library is added, because i've a problem with IPS – Scorpy86 Jul 18 '13 at 09:49
  • 1
    http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting – Adam Pearce Jul 18 '13 at 15:32

1 Answers1

2

The problem is that you are using tick before its definition in one case and after its definition in the other case.

In the first case:

force.on("tick", tick);

function tick () { /* ... */ }

the function tick is defined at parse time and is available to be passed as the second argument.

On the other hand in:

force.on("tick", tick);

var tick = function () { /* ... */ };

the variable tick is defined at parse time (so JSHint does not complain), but it gets its value only at runtime. Its value is undefined when force.on("tick", tick) is executed.

The difference is more apparent when you consider the following example:

var f;
if (true) {
    f = function () { return 1; };
} else {
    f = function () { return 2; };
}

f(); // returns 1

versus:

if (true) { 
    function f () { return 1; }
} else { 
    function f () { return 2; }
}

f(); // returns 2, from the latest definition

See this question to understand the difference between using the var tick = function () ... and function tick() ... better.

Community
  • 1
  • 1
musically_ut
  • 34,028
  • 8
  • 94
  • 106