JavaScript functions are defined with the function keyword. You can define a
function as a declaration or as an expression. Each
method has its own rules and use cases.
A function declaration is the standard way to define a function. Declared functions are hoisted, meaning they can be called before they are defined in the code.
function myFunction(a, b) {
return a * b;
}
A function can also be defined using an expression. A function expression can be stored in a variable. These functions are often anonymous (they have no name).
const x = function (a, b) { return a * b };
let z = x(4, 3); // The variable acts as the function name
Functions can be made "self-invoking," meaning they execute automatically without being called. You do this by wrapping the function in parentheses.
(function () {
let x = "Hello!!"; // I will invoke myself
})();
In JavaScript, functions are objects. They have both properties and methods.
arguments.length — Returns the number of arguments received when the
function was invoked.toString() — Returns the function as a string.Arrow functions allow a short syntax for writing function expressions. They do not have
their own this, which makes them very useful in certain scenarios.
// Traditional
const x = function(x, y) {
return x * y;
}
// Arrow
const y = (x, y) => x * y;