Aibin
Aibin

Reputation: 71

Why can't function declaration be accessed after enclosed in parentheses?

The function declaration can no longer be accessed by its name:

(function log(){
  console.log('print some information')
})
log()

The code throw reference error. My understanding with that is: function log doesn't live in any inner scope, why can't I call it by its name?

Upvotes: 0

Views: 50

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50854

why can't I call it by its name?

When you put parenthesis around your function, you get a function expression, and not a function declaration, as the parser expects to see an expression between the () and not a declaration. Function expressions names can only be accessed locally to that function:

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope)

- MDN

The same applies for other operators such as ! and +, not just (), which makes your function be treated as a function expression.

If you were wanting to make a function declaration, you can remove the parenthesis:

function log(){
  console.log('print some information');
}
log();

Upvotes: 3

Related Questions