Here is detailed explanation of Functions:
In JavaScript, a function is a reusable block of code that performs a specific task or set of tasks.
• Functions allow you to encapsulate code, making it modular and easier to manage.
Defining a Function:
- Function Declaration
function functionName(parameters) {
// Code to be executed
}
- Function Expression
const functionName = function(parameters) {
// Code to be executed
};
- Arrow Function (ES6+)
const functionName = (parameters) => {
// Code to be executed
};
Function Parameters and Arguments:
- Parameters: Variables listed in the function definition.
function add(x, y) {
// x and y are parameters
return x + y;
}
- Arguments: Values passed to a function when it is called.
const result = add(5, 3); // 5 and 3 are arguments