5

Hi I'm new to Javascript, and I'm reading the Oreilly's Javascript the definitive guide. In the declaration statement section it says:

enter image description here

I made a simple test:

var a = 1;
while(a < 5){
    a++;
    function double(a){return a * 2 };
    console.log(double(a));
}    

It seems the node.js doesn't give me any error and run as expect. Any comment on this?

mko
  • 21,334
  • 49
  • 130
  • 191
  • 2
    Run it in strict mode, and you'll get your error. It's invalid syntax *(except if Mozilla's JS implementation where there's a similar syntax allowed)*, but has historically been permitted by implementations. – the system Mar 02 '13 at 00:04

1 Answers1

-1

That's not true. However you should keep in mind that they may not behave as you might expect.

For instance, this will work:

if( false) {
    function double(a) {return a*2;};
}
else {
    console.log(double(4));
}

Even though you might think the function is never defined due to being inside an if that is never reached, the function is in fact hoisted to the top of the current "block" (be it a containing function or the entire <script> tag or file) and are therefore accessible anywhere.

You shouldn't put function definitions inside an if block, but there's no reason why you can't.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    there's plenty reasons you shouldn't - 1. the spec says not to, 2. on some browsers, it doesn't work! – Alnitak Mar 02 '13 at 00:21
  • @Alnitak I specifically said you shouldn't. However according to the specifications on hoisting it's exactly the same as `var`. – Niet the Dark Absol Mar 02 '13 at 00:22
  • It's not valid according to the spec, so what the specification describes about "hoisting" *(a term not used in the spec)* doesn't apply. The implementations may allow it, and may treat its hoisting the same, but it still isn't valid. – the system Mar 02 '13 at 00:42