Can we define a "function declaration" also as a "function statement"?

Viewed 72

This question born considering the function declarations VS function expressions.

We clearly know that a function declaration have this form

function foo() { 
    var a = 3;
    console.log( a );
}

while a function expression can have this form (appearing like what is known like Immediately invoked function expression)

(function foo() { 
    var a = 3;
    console.log( a );
})()

Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.

Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).

So, can you give some help, I'm a little confused. A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?

I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?

2 Answers

While the syntax of a function expression is the same as a function declaration, they're not the same thing.

The scope of the name used in function declarations is different from named function expressions. When you write:

function foo() { 
    var a = 3;
    console.log( a );
}

the scope of foo is the enclosing function (or the global environment if this is at top level).

When you write:

(function foo() { 
    var a = 3;
    console.log( a );
})

the scope of foo is just the body of the function.

The parser determines whether it's a function expression or declaration based on the context. Since a statement can't be inside parentheses, putting parentheses around it forces it to be an expression.

In expression hoisting will not happened, but in function statement hoisting is occurred.

In function statement, You can write function definition anywhere in js file before or after function call. JIT compiler will hoisting at top of programming file.

For function expression, JIT compiler will not do as same as function statement, which reads where its occurred. If you try to access function before its defined it will show type error.

IIFE is pattern mostly used to avoid access variable outside function.

callMe();  // Function statement

function callMe(){

return console.log("I am function statement");
}


// callMe2();  // TypeError if you call before expression defined.

var callMe2 = function(){
  return console.log("I am function expression");
};

callMe2(); //Function expression call

(function(){
return console.log("I am IIFE");
}());

Related