3

this code doesn't work

for (let i = 0; i < 10; i++) {
  console.log("ddd")
  (function x() {
    console.log("eee")
  })();
}

VM531:3 Uncaught TypeError: console.log(...) is not a function at :3:3

these two works just fine

for (let i = 0; i < 10; i++) {
  (function x() {
    console.log("eee")
  })()
  console.log("ddd")
}

for (let i = 0; i < 10; i++) {
  (function x() {
    console.log("eee")
  })()
}
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
fasy
  • 45
  • 4

1 Answers1

4

You need to have a semicolon after the console.log - otherwise it's trying to call the returned result of console.log (undefined) which isn't a function, which is calling your error.

Automatic semicolon insertion doesn't take into account whitespace.

for (let i = 0; i < 10; i++) {
  console.log("ddd");
  (function x() {
    console.log("eee")
  })();
}

Your code was trying to do:

console.log("ddd")(function x() {...})()

Which turns out to be:

undefined(function x() {...})()

Which results in your TypeError.

This problem of brackets overlapping due to a lack of semicolons is similar to my answer on this question.

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67