Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous javascript function call !function vs function [duplicate]

Tags:

javascript

How come

function(){ alert("test123");}()

produces SyntaxError: Unexpected token (

while

!function(){ alert("test123");}()

alerts "test123"

?

like image 384
Alon Avatar asked Oct 22 '22 02:10

Alon


1 Answers

It's because by adding ! sign you convert the declaration into an expression and invoke it immediately. By enclosing your function into brackets you will make first example working without errors:

(function(){ alert("test123");})()

To make it clearer you can think about first expression as something like:

if (false || !function(){ return false; }())


And as @zerkms noticed there is a complete explanation of Immediately-invoking functions.
like image 136
Anatolii Gabuza Avatar answered Oct 29 '22 21:10

Anatolii Gabuza