0

I'm learning Node.js, and there is something I cannot understand.

I have a function and a Immediately Executing Function, like this:

(
    function foo(){
        console.log('foo was executed')
    }
)()

function foofun(){
    return 123
}
console.log(foofun())

When the IEF is at the beginning, the code executes right, but when the foofun() and it's console.log are at the beginning, this gave me this error:

enter image description here

Does it matters the position where is located the IEF? Why this happens?

Liam
  • 22,818
  • 25
  • 93
  • 157
Ivan Parra
  • 135
  • 9
  • 3
    Do you have any code after or before that? The problem is likely that you are not using semicolons to terminate statements. The JavaScript engines interprets two expressions that you intended to be separate statements as a single statement. The error means that the engine tries to call the return value of `console.log(...)` as a function, but we all know that `console.log` doesn't return anything. – Felix Kling Jan 25 '21 at 16:15
  • 3
    On its own the code doesn't throw an error. – Felix Kling Jan 25 '21 at 16:18
  • @FelixKling Oh right. It is curious because based on what I read, semicolons are no longer needed in js, but, if I put it only after the (console.log(foofun()) it executes right. Thank you. – Ivan Parra Jan 25 '21 at 16:20
  • 2
    [Semicolons are not required, but should be used](https://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) – Liam Jan 25 '21 at 16:21
  • 2
    By the way, it is IIFE (Immediately Invoked Function Expression), not IEF ;) – secan Jan 25 '21 at 16:22
  • 6
    JavaScript has *automatic semicolon insertion*, but it [might not work as you expect](https://stackoverflow.com/q/2846283/218196). And instead of learning the rules of ASI, I find it much easier to just always use semicolons :D – Felix Kling Jan 25 '21 at 16:23

0 Answers0