Question about function syntax

what is the difference between

function test(nom){

 console.log("hello " + nom);

}

console.log(test("bilal"));

and

(function(nom){

   console.log("hello" + nom)

})("bilal");

The second code example is an IIFE.

The first function has to be explicitly called in order to execute. The second (because of the trailing parentheses) is being immediately executed, with no user intervention. As @lasjorg points out, it is referred to as an IIFE, or immediately invoked function expression.

The second is often used to perform some initialization behavior, or to assign a “closure” to a variable. You’ll see it used later, when you start exploring design patterns (and if you’re ready for that, Google “Addy Osmani Design Patterns” for a good look at them).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.