6Functions
A function is an independent block of code (instructions list), which can be called from another part of the code. This requires a mechanism for storing the calling line, sharing variables, passing parameters and returning a value.
In JavaScript, a function is a “first-class object”, which means that a function can:
- – be assigned to a variable;
- – be an argument to other functions;
- – be returned as a value;
- – have properties, methods and a prototype, like every other object.
To illustrate this notion, we present a “prototypal diagram”, as in Chapter 5, which shows how intricate “Object” and “Function” are:
Object.constructor = FunctionObject [[prototype]] === Function.prototypeObject.prototype.constructor = ObjectObject.prototype [[prototype]] === null // aloneFunction.constructor = Function // itselfFunction [[prototype]] === Function.prototypeFunction.prototype.constructor = FunctionFunction.prototype [[prototype]] === Object.prototype
This chapter presents the notions of “scope” and “execution context”, which will shed light upon the mechanisms of “function closure” and “IIFE” (immediately invoked function expression).
The diagram below summarizes what will be detailed, and where the notions of free variables and bound variables will be used.
6.1. General syntax of a JavaScript function
A function can be set for the same syntax in two ways: by ...