0

The below works as intended

var dogName = function animalName(name) {
  console.log("My name is " + name);
}

dogName('Scruffy');

(function () {
    console.log("My name is Fido!");
})();

If you comment out dogName('Scruffy'); it outputs this

My name is function () {
  console.log("My name is Fido!");
}

If you adjust the IIFE to

(function () {
  console.log("My name is Fido!");
}()); // ()) instead of )()

It outputs

My name is Fido!
My name is undefined

Why does the functional expression use the IIFE as it's name variable, and why is the IIFE executed first before the functional expression in the last example?

Chad
  • 560
  • 4
  • 15
  • 1
    If you comment out the intermediate line which contains a clear semicolon, it becomes `function animalName(name) {...}(function ...)`… An IIFE. Put a `;` after the definition of `animalName`. – deceze Feb 02 '17 at 20:10
  • 1
    Related: [`TypeError`: `console.log(`…`)` is not a function](http://stackoverflow.com/q/31013221/4642212). – Sebastian Simon Feb 02 '17 at 20:13

1 Answers1

4

The problem is that you aren't putting a semi-colon at the end of your function expression. Your code is essentially interpreted as this:

var dogName = function animalName(name) {
  console.log("My name is " + name);
}(function () {
    console.log("My name is Fido!");
})();

As far as the interpreter can tell, you're passing a function as the first argument to a named function expression then attempting to call the return value as a function.

To fix this, just put a semicolon at the end of the expression.

var dogName = function animalName(name) {
  console.log("My name is " + name);
}; // <--

(function () {
    console.log("My name is Fido!");
})();
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85