Js Functions
Js Functions
ABADIR HASSAN
Functions
Function declarations
A function definition (also called a function declaration, or function statement) consists
of the function keyword, followed by:
While the function declaration above is syntactically a statement, functions can also be
created by a function expression.
Such a function can be anonymous; it does not have to have a name. For example, the
function square could have been defined as:
const square = function (number) {
return number * number;
};
const x = square(4)
Calling functions
Defining a function does not execute it. Defining it names the function and specifies
what to do when the function is called.
Calling the function actually performs the specified actions with the indicated
parameters. For example, if you define the function square, you could call it as follows:
square(5);
function square(n) {
return n * n;
}
console.log(square(5));
Function parameters
There are two special kinds of parameter syntax: default parameters and rest parameters.
Default parameters
In JavaScript, parameters of functions default to undefined. However, in some situations it might
be useful to set a different default value. This is exactly what default parameters do.
In the past, the general strategy for setting defaults was to test parameter values in the body of the
function and assign a value if they are undefined.
In the following example, if no value is provided for b, its value would be undefined when
evaluating a*b, and a call to multiply would normally have returned NaN. However, this is
prevented by the second line in this example:
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
multiply(5);
Arrow functions
An arrow function expression (also called a fat arrow to distinguish from a hypothetical -
> syntax in future JavaScript) has a shorter syntax compared to function expressions and
does not have its own this, arguments, super, or new.target. Arrow functions are always
anonymous.
let myFunction = (a, b) => a * b;