In JavaScript, a function is a block of code that is defined once and can be executed multiple times. Functions are a fundamental building block of the language, and they can be used in a variety of ways.
Here are some key points about functions in JavaScript:
- Functions are defined using the
function
keyword, followed by the function name, a set of parentheses, and a set of curly braces that contain the code for the function. - Functions can take zero or more arguments, which are values that are passed into the function when it is called. The values passed in are called “parameters.”
- Functions can return a value using the
return
keyword. If a function does not return a value, it returnsundefined
by default. - Functions can be defined as part of an object (in which case they are called “methods”) or as standalone functions.
- Functions can be stored in variables, arrays, or objects, and they can be passed as arguments to other functions.
Here is an example of a simple function that takes two arguments and returns their sum:
function add(x, y) {
return x + y;
}
console.log(add(2, 3)); // outputs 5
Functions can also be defined using function expressions, which are a more concise syntax for defining functions. Here is the same function defined using a function expression:
const add = function(x, y) {
return x + y;
};
console.log(add(2, 3)); // outputs 5
In modern JavaScript, you can also define functions using the “arrow function” syntax, which is even more concise than function expressions. Here is the same function defined using an arrow function:
const add = (x, y) => x + y;
console.log(add(2, 3)); // outputs 5