Home > Blockchain >  why JavaScript report an error when I code like this?
why JavaScript report an error when I code like this?

Time:09-06

If i code like

function foo() {
  console.log(123);
}(6)

execute this code snippet, console.log nothing

but

function foo() {
  console.log(123);
}()

the code snippet will produce SyntaxError


(6) might be regarded as expression, it's no relation with function declaration.

But next code snippet, it seems as interpreter precompiled it. Then function declaration will be hoisted.

It's my guessing.

CodePudding user response:

When you do this:

function foo() {
  console.log(123);
}(6)

The javascript engine sees it as two different expressions, like this:

function foo() {
  console.log(123);
};
(6);

So basically, one function declaration and just a random 6.

When you do the second one:

function foo() {
  console.log(123);
}()

The engine sees it the same as before, as two different expressions, but the second expression, (), is not valid on its own. Hence the error.

function foo() {
  console.log(123);
};
();

Just adding this here since it's syntactically very close(Thanks @RickN).

(function foo() {
  console.log(123);
})(6)

This will call the function with one parameter, 6. This means that this will log 123 to the console. This is called an Immediately Invoked Function Expression or an IIFE The first one is not logging anything because the function is not being called.

  • Related