It will be a long answer, but it will give you the necessary background. There are two ways to define functions in JavaScript: Function Definition (Classic View)
function foo() {
and then a more hidden type, function expression
var bar = function() {
Essentially, the same thing happens when executed. A functional object is created, memory is allocated, and the identifier is bound to this function. The difference is in the syntax. The former is itself an expression declaring a new function; the latter is an expression.
An expression of a function enables us to insert a function in any place where a normal expression would be expected. This enables anonymous functions and callbacks. Take for example
setTimeout(500, function() {
Here an anonymous function will be executed whenever it says setTimeout. However, if we want to immediately execute a function expression, we need to make sure that the syntax is recognized as an expression, otherwise we have an ambiguity as to whether we mean a function expression or an operator.
var fourteen = function sumOfSquares() { var value = 0; for (var i = 0; i < 4; i++) value += i * i; return value; }();
Here sumOfSquares is called immediately because it can be recognized as an expression. fourteen becomes 14 , and sumOfSquares collects trash. In your example, the grouping operator () forces its contents to an expression, so the function is an expression and can be called immediately as such.
It is important to note that the difference between my first example foo and bar is the rise. If you donβt know what it is, you should say a quick Google search or two, but a quick and dirty definition is that lifting is JavaScript behavior to bring declarations (variables and functions) to the top of the field. These declarations usually only raise the identifier, but not its initialized value, so the entire scope will be able to see the variable / function before it is assigned a value.
This is not the case with function definitions; the entire declaration is declared here and will be visible in the entire content area.
console.log("lose your " + function() { fiz();