Functions
suggest changeFunctions in JavaScript provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in JavaScript.
Syntax
-
function example(x) { return x }
-
var example = function (x) { return x }
-
(function() { … })(); // Immediately Invoked Function Expression (IIFE)
-
var instance = new Example(x);
-
Methods
- fn.apply(valueForThis[, arrayOfArgs])
- fn.bind(valueForThis[, arg1[, arg2, …]])
- fn.call(valueForThis[, arg1[, arg2, …]])
-
ES2015+ (ES6+):
- const example = x => { return x }; // Arrow function explicit return
- const example = x => x; // Arrow function implicit return
- const example = (x, y, z) => { … } // Arrow function multiple arguments
- (() => { … })(); // IIFE using an arrow function
Remarks
Arrow functions are covered in Arrow functions. An arrow has no own this, arguments, or prototype, and it cannot be used with new.
Immediately Invoked Function Expressions (IIFE)
Variadic function (with arbitrary number of arguments)
Passing arguments by reference or value
Function arguments, the arguments object, rest, and spread
Get the name of a function object