Javascript - Function Declaration

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

A function declaration is one of the several grammar syntax that permits to define a function.

The execution of a function declaration can be done before the function declaration definition.

This is not the case with a function expression.

A function declaration defines a function and binds it to a variable in the current scope.

Advertising

3 - Syntax

  • The function name is mandatory.
  • The function declaration cannot be written inside a code block that is not a declaration function
function name([param,[, param,[..., param]]]) {
   [statements]
}

4 - Function Execution Context

As every function, a function declaration follows the context principle.

// The global context
function globalFunction() {
 
  // Inside another function
  function innerFunction() {}
}

5 - Example

At the top level of a program, the below declaration would create a global function called add.

/* The execution of a function declaration can be done before the function declaration definition */
/* This is not the case with a function expression */
console.log(add(2,3));
 
/* The function declaration definition */
function add(a,b) {
     return a+b;
};
 
console.log(add);

6 - Documentation / Reference

web/javascript/es/function_declaration.txt · Last modified: 2019/02/16 17:40 by gerardnico