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.

Syntax

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

functionName(arg1,...argN)

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 its definition.
  • The function expression is a text that can be assigned to a variable and executed afterward. The function is not added to the global context and can therefore not be called from everywhere.
  • The function constructor. You can create dynamically a function with a Function with a text as parameter.

Declaration

A Javascript - Function Declaration is a fix function declaration.

function add(a,b) {
     return a+b;
};

Expression

A Function Expression is just a function expression stored in a variable.

var add = function myOptionalName(x, y) {
   return x + y;
};
 
console.log(add(2,3))

Constructor

See Javascript - Function Constructor (Dynamic Coding)

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

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));

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";
    // this is set to the top browser scope
    this.window.bar = "bar IFFE variable";
    console.log( "Hello!" ); 
})(); // "Hello!"

// foo is not defined in the global scope
if (typeof foo == 'undefined') {
   console.log("foo is undefined");
}

if (typeof window.bar == 'undefined') {
   console.log("bar is undefined");
} else {
   console.log("window.bar is defined with the value ("+window.bar+")");
}

Management

Signature / Argument

Position

// ECMAScript 2015 allows default parameters in the signature
foo = function (a='default',b='default'){ 
   console.log('a has the value '+a);
   console.log('b has the value '+b);
};
console.log('Passing values:');
foo('A','B');
console.log('\nWith Default values:');
foo();

Name

JavaScript does not have native support for named parameters

Argument

Static / Lexical
foo = function (first, second){ 
  console.log('There is two arguments: '+first+' and '+second);
};

foo('B','A');
Dynamic Argument
foo = function (){ 
   for (i = 0; i < arguments.length; i++) {
        console.log('Argument '+i+' has the value '+arguments[i]);
    }
};

foo('B','A');

Scope

Variables

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

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);

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

Object

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

Javascript Function Method

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.

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();

Argument

Test if an argument was defined with undefined

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

List

You can list all the function by inspecting the window object. See Javascript - (Firefox) Scratchpad

Type

You can use the Javascript - Type operator to test if a property is a function.

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")
}

Typescript: How to test that a variable is a function?

To avoid TS2349: This expression is not callable, you can test your variable with the following expression.

initialState instanceof Function ? initialState() : initialState;

Documentation / Reference