rauschma / exploring-js

20 stars 0 forks source link

Precision #49

Closed eric-the-snake closed 5 years ago

eric-the-snake commented 5 years ago

Hi ... I am reading your excellent document and just tought you may want to add precisions on the affirmation (section 6.5.3) :

Additionally, you can’t put a function call immediately after a function declaration.

Actually,

function dummy (x) { console.log(x) }('abc');

is working ... Is it right to say it's a declaration being called right after?

rauschma commented 5 years ago

This definitely does look like an immediately-invoked function declaration and had me stumped for a while (Node.js REPL):

> function dummy (x) { console.log(x) }('abc')
'abc'
> dummy
[Function: dummy]

However, something different is going on. A first clue: If this really were a function call, then you’d see the result undefined somewhere. The following example exposes what really happens:

> function dummy(x) { console.log('->' + x) }('abc')
'abc'

That is, the string 'abc' is treated as a statement. And the Node.js REPL always returns the value of the last statement (the “completion value”) – for example:

> if (true) 'yes'; else 'no';
'yes'
> if (false) 'yes'; else 'no';
'no'