☰ See All Chapters |
JavaScript ES6 Functions
A function is a named subroutine that accepts zero or more arguments and returns one value or may not return any value. JavaScript ES6 has concept of classes, namespaces, and modules, but functions still are an integral part in describing how to do things. JavaScript ES6 also allows adding new capabilities to the standard JavaScript ES5 functions to make the code easier to work.
Function Syntax
function functionName(parmeter1, parmeter2 ...) { return value; //Or return nothing } |
Example
function sum( x , y ){ return x + y; } Sum(6+4); |
Immediately invoked function expressions
If function has to be invoked immediately once after its definition, then function can be called by surrounding the definition with parentheses, followed by parameters in parentheses. For example, the following code defines and invokes the sum function:
(function sum( x , y ){ return x + y; } )(10, 20); |
These functions are called immediately-invoked function expressions, or IIFEs.
JavaScript ES6 Anonymous Functions
We can assign a function to a variable, as an example, the following code sets sum variable equal to a function that receives sum of two numbers.
var sum = function ( x , y ) { return x + y; } |
When you are assigning function to a variable, the function doesn't need a name. These types of functions are anonymous functions.
Arrow Function Expressions
To simplify anonymous functions declaration, JavaScript ES6 supports arrow function expressions, also Lovingly called the fat arrow functions (because -> is a thin arrow and => is a fat arrow) and also called a lambda function (because of other languages).. This requires two changes:
The function keyword is removed.
An arrow, =>, is inserted between the parameter list and the function's code block.
For example, the following code shows what the preceding declaration looks like with proper JavaScript ES6 and arrow function syntax:
let sum = (x, y) => { return x + y; }; |
If there is only one parameter, you can remove the parentheses from the parameter list.
let squareValue = x => { return x * x; }; |
If there is only a single line which is single return statement inside function block curly braces around the code block can be removed along with removal of return keyword.
let squareValue = x => x * x; |
All Chapters