JSFiddle - React, Tailwind, and code Playground

by fparent

JavaScript

// Named Function Expression
var foo = function bar() { /* code */ };

// Anonymous Function Expression
var foo = function() { /* code */ };

// Function Declaration
function foo() { /* code */ }


// Even though this syntax might look right, you can't just put a set of parens 
// after a function declaration to execute it because the grouping operator needs 
// to contain an expression.
//
// function foo() { /* code */ } ();
// > Uncaught SyntaxError: Unexpected token )


// Function Expression used à-la Crockford; more readable and conventional
(function() { console.log( 'function0' ) } ());

              
// Alternative ways of declaring an IIFE                        
// "If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator."        
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/ 
              
!function(){ console.log( 'function1' ) }();
~function(){ console.log( 'function2' ) }();
-function(){ console.log( 'function3' ) }();
+function(){ console.log( 'function4' ) }();
                          
// Twitter uses this form in the minimzed script called to initialize their sharing buttons
// <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0] ...

             
// Obviously the return value will be altered when using unary operator
// and the result can be unexpected, so use with caution, if not at all!
console.log(
    !function(){ return( 'won\'t be displayed...' ) }()
);
                 
console.log(
    (function(){ return( 'returned value' ) } () )
);