Javascript - Functions

1 - About

Functions functionalities in Javascript.

A function in Javascript is a variable that’s given a reference to the function being declared. The function itself is a value (as an integer or an array) that contains an expression.

JavaScript functions are first-class objects.

Every function is an object: a Function object and retains then its state.

Functions are a subtype of objects — typeof returns “function”, which implies that a function is a main type — and can thus have properties,

Variables and functions defined within a function may only be accessed inside that context. They are private.

Functions in Javascript fulfill multiple distinct features:

  • procedures,
  • constructors,
  • classes
  • and modules.

functions, methods, and class constructors are just three different usage patterns of function.

3 - Syntax

Parentheses are used to execute a function. All constructs of the below form are then function.

functionName(arg1,...argN)

4 - Initialization

You can (initialize|declare) a function through 3 constructs:

  • The function declaration. The standard function declaration. This function is added to the global context. It's execution can be called before it's definition.
  • The function expression is a text that can be assigned to a variable and executed afterwards. The function is not added to the global context and can then not be called from everywhere.
  • The function constructor. You can create dynamically a function with a Function with a text as parameter.

4.1 - Declaration

A Javascript - Function Declaration is a fix function declaration.

4.2 - Expression

A Function Expression is just an expression (a text) that you can:

  • execute by adding its signature ([param,[, param,[…, param]]])
  • pass as argument to an other function

4.3 - Constructor

See Javascript - Function Constructor (Dynamic Coding)

new Function ([arg1[, arg2[, ...argN]],] functionBody)

4.4 - Arrow Expression

An arrow function expression has a shorter syntax than a function expression and does not bind a lot of environment element (this, …).

var area = (r) => Math.PI * r ** 2;
var rayon = 3;
console.log("The area of a circle with the rayon "+rayon+" is "+area(rayon));

4.5 - Immediately invoked function expression (IIFE)

An IIFE is often used to create a scope in order to declare variables that won’t affect the surrounding code outside of it.

(function IIFE(){
    var foo = "IFFE variable";
    console.log( "Hello!" ); 
})(); // "Hello!"
 
// foo is not defined in the global scope
if (typeof foo == 'undefined') {
   console.log("foo is undefined");
}

5 - Management

5.1 - Scope

5.1.1 - Variables

A function can refer to any variables in its scope, including the parameters and variables of outer functions (ie outer scope).

5.1.2 - Block-local

A block local function is inside a define inside local blocks or substatements (such as if then else).

JavaScript implementations report them as an error in strict mode. Block local function must be avoid> Most of the function must be put at the outermost level of its parent function. Until ES5, the standard did not even acknowledge the existence of block-local function declarations.

Example: The result could be “local” :(

var fs = [];
 
function f() { return "global"; }
 
if (false) {
        function f() { return "local"; } // block-local
        fs.push(f());
}
fs.push(f());
console.log(fs);

5.2 - Return

The return statement return the result variable out of the function so it is available to use.

This is necessary because variables defined inside functions are only available inside those functions. See execution context

5.3 - Object

A Function is an object that inherit its methods from Function.prototype.

where:

  • apply(): Calls a function and sets its this to the provided value, arguments can be passed as an Array object.
  • bind(): Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called. See Javascript - bind method
  • call(): Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are. See Javascript - Call method
  • caller: Specifies the function that invoked the currently executing function.
  • isGenerator(): Returns true if the function is a generator; otherwise returns false
  • length: Specifies the number of arguments expected by the function.
  • toLocaleString returns the result of calling toString().
  • toSource(): Returns a string representing the source code of the function.
  • toString(): Returns a string representing the source code of the function.
  • name: The name of the function.

5.4 - State

A function is an object that creates a context and retains its state. See Javascript - Closure

function makeCounter() {
 
  var i = 0;
 
  return function() {
    console.log( ++i );
  };
 
}
 
var counter = makeCounter();
counter();
counter();
counter();
counter();

5.5 - Argument

Test if an argument was defined with undefined

if (typeof sec === 'undefined') sec = 2000;

5.6 - List

You can list all the function by inspecting the window object. See inspect

5.7 - Type

To test if a property is a function, you can use the typeof operator.

Example:

var element = document.querySelector("body");
 
if (typeof element.childElementCount !== 'function') {
    console.log("element.childElementCount is a function")
} else {
    console.log("element.childElementCount is not a function")
}

6 - Documentation / Reference

lang/javascript/es/function.txt · Last modified: 2017/09/28 23:05 by gerardnico