Randomblue
Randomblue

Reputation: 116373

TypeError with two consecutive self-executing anonymous functions

This question is inspired from the accepted answer here. Why does the following piece of code alert "first", then "second", then errors out with a TypeError?

(function() {
    alert('first');
}())


(function() {
    alert('second');
}())

The given explanation is that the returned value of the first function is trying to get called. But why did that happen? [Also, why didn't semi-colon insertion add a semi-colon after the first self-execution?]

Upvotes: 5

Views: 855

Answers (3)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5713

It happened because that's the way your program was parsed. We could sumarise the program as

 (some stuff) (some more stuff)

And it's clear that this should try to call the some stuff as a function. Of course a semi-colon would fix the problem and you were hoping that semi-colon insertion would have done it automatically for you. Without knowing the detailed insertion rules, I would just say that nothing was inserted becuse the rules are specifically designed to not change otherwise well defined behaviour.

Of course, you might not consider this behaviour "well defined". But language rules never work well in every situation.

Upvotes: 1

Zirak
Zirak

Reputation: 39848

ASI, Automatic Semicolon Insertion. Your code should've been written like this:

(function() {
    alert('first');
}()); //<--semicolon


(function() {
    alert('second');
}()); //<--semicolon

Instead, here's the step that are taken:

(function() {
    alert('first');
}())


(function() {
    alert('second');
}())

//now, the interpreter guesses that you mean to concatenate the two
(function() {
    alert('first');
}())(function() {
    alert('second');
}());
//it also inserts a semi-colon where it should've appeared at the end of the script

//first function doesn't return anything === returns undefined
undefined(function() {
    alert('second');
}());

//second function doesn't return anything === returns undefined
undefined(undefined);
//however, the braces stay, since they can also mean function execution

undefined is not a function, therefore it cannot be executed, therefore, you get a TypeError.

Upvotes: 2

pimvdb
pimvdb

Reputation: 154918

Without semicolons it will evaluate to:

(function() {
    alert('first');
}())(function() {
    alert('second');
}())

The first function is executed, and since it does not return anything, it evaluates further to:

undefined(function() {
    alert('second');
}())

Then the second function is executed, and it returns again undefined, so:

undefined(undefined)

Which does not work of course (TypeError since undefined is not a function). Separate function calls should be separated with a semicolon, as every statement should actually be.

Upvotes: 6

Related Questions