1

In reading about javascript functions, I understand that you can call a function immediately after defining it thusly:

al = function(string){
 alert(string)
}("test");

but that you cannot do the same thing with empty parens:

al = function(){
 alert("test")
}();

and that, instead, you have to convert the function into a function expression:

al = (function(){
 alert("test")
})();

Why is this, and why does the first code example work correctly without this conversion?

asked Mar 10, 2013 at 23:35
7
  • 6
    You're thinking of something else. All of your examples work. You probably mean the case in which you don't have the assignment, because in that case the leading keyword function signals a function declaration, and not a function-call expression that starts with an anonymous function. Commented Mar 10, 2013 at 23:39
  • I would be surprised if your second case doesn't work !! Commented Mar 10, 2013 at 23:40
  • ah ok, so if I do all of the above without assignment, they will break? Commented Mar 10, 2013 at 23:40
  • Yes, please redo the second one without the assignment and see what happens. Commented Mar 10, 2013 at 23:41
  • 1
    These all work as they're function expressions rather than function declarations. Stripping the al = from either the 1st or 2nd example will create a declaration, which cannot be followed by calling parenthesis. Stripping it from the 3rd, the extra parenthesis still make it an expression. Commented Mar 10, 2013 at 23:43

1 Answer 1

2

All three of your examples are more or less identical. Note that the al = does nothing functionally because none of these functions return anything, so al will be undefined. If they did return something, it would be assigned to al. al = is necessary for the first two expressions to be syntactically correct.

The first example is different in that it takes an argument. The other two don't, but that has no effect on how the expression works.

The parentheses can also be used to signal an expression. For example, (function () {})() is valid syntax, but function () {}() is not. = also signals an expression, so variableName = function () {}() also works.

answered Mar 11, 2013 at 1:05
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.