Chapter 21: Functions in Javascript
Functions in Javascript are one of the main building blocks of a program. A function is a Javascript procedure - a set of instructions that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you want to call it.
Defining functions
A function in Javascript is defined with the keyword "function", followed by a name, followed by parentheses ().
function functionName() {
// code to be executed
}
Brackets can include parameter names separated by commas: (parameter1, parameter2, ...)
Parameters vs Arguments
The terms parameters and arguments can be used for the same thing: information that is passed to a function.
Of a function, the parameters are the names listed in the function definition.
The arguments are the actual values received by the function when it is invoked.
When you invoke a function, you can pass arguments to it. Arguments are the values you pass to the function.
Invoking functions
A function will execute your code when you call it. You call a function by referring to its name, followed by parentheses.
FunctionName();
When a function is called, arguments are passed to the function as inputs, and the function can process them to produce an output.
Return functions
A function can have an optional return statement. The return statement ends execution of the function and specifies a value to be returned to the calling function.
function myFunction() {
return value;
}
Anonymous functions and function expressions
Functions do not need to have a name. You can create anonymous functions or function expressions.
An anonymous function is a function without a name. Anonymous functions are typically assigned to variables or used as arguments to other functions.
var myFunction = function() {
// code to be executed
}
A function expression is similar to an anonymous function, except that it is used as part of a larger expression, such as an arithmetic operation or a function call.
(function() {
// code to be executed
})();
Arrow functions
Arrow functions are a new syntax for writing functions in Javascript introduced in ES6. They are shorter and easier to write than traditional functions.
var myFunction = () => {
// code to be executed
}
Arrow functions have some differences from normal functions. The most notable is that the value of "this" within an arrow function is determined by the invocation context, not the function itself.
In summary, functions are a vital part of Javascript and are used to encapsulate code so that it can be reused. They can take arguments, return values, and be named or anonymous. With the advent of ES6, we also have the option to use arrow function syntax for more concise code writing.