Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the exclamation mark do before the function?

!function () {}(); 
like image 328
Sebastian Otto Avatar asked Sep 20 '10 21:09

Sebastian Otto


People also ask

What is the exclamation mark used for in Excel formulas?

Excel allows you to refer to any cell on any worksheet, which can be especially helpful if you want to reference a specific value from one worksheet to another. To do this, you'll simply need to begin the cell reference with the worksheet name followed by an exclamation point (!).

What does the exclamation mark mean symbol?

The exclamation mark, !, or exclamation point (American English), is a punctuation mark usually used after an interjection or exclamation to indicate strong feelings or to show emphasis.


1 Answers

JavaScript syntax 101: here is a function declaration:

function foo() {} 

Note that there’s no semicolon; this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn’t invoke the function, of course, but we can now put () at the end: !function foo() {}(), which has higher precedence than ! and instantly calls the function.

function foo() {}() would be a syntax error because you can’t put arguments (()) right after a function declaration.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})(); 

Lastly, ! makes the expression return a boolean based on the return value of the function. Usually, an immediately invoked function expression (IIFE) doesn’t explicitly return anything, so its return value will be undefined, which leaves us with !undefined which is true. This boolean isn’t used.

like image 58
Neil Avatar answered Sep 30 '22 23:09

Neil