Functions in JavaScript are blocks of code that can be defined once and reused multiple times throughout your program. They encapsulate a set of instructions and can accept input values, process them, and optionally return a result.
Anonymous functions are functions without a designated name. They are often used as arguments for other functions, or in scenarios where a short-lived function is required.
Example:
let sum = function(x, y) {
return x + y;
};
console.log(sum(3, 5)); // Output: 8
Function Expressions:
Function expressions are a way to define functions as values within variables. This allows you to treat functions like any other data type and pass them around in your code.
Example:
let multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 4)); // Output: 8
Function Parameters:
Function parameters are the placeholders for values that a function can accept when it's called. These values are then used within the function's code.
Calling a function means executing the code within the function's body. This is done by using the function's name followed by parentheses.
Example:
function double(num) {
return num * 2;
}
let result = double(7);
console.log(result); // Output: 14
Arrow Functions (ES6):
Arrow functions are a concise way to write functions introduced in ES6. They have a simpler syntax and automatically capture the 'this' value of the surrounding context.
Example:
let divide = (x, y) => x / y;
console.log(divide(10, 2)); // Output: 5
Return Keyword:
The 'return' keyword is used within a function to specify the value that the function should produce as its output. Once a 'return' statement is encountered, the function exits.
Example:
function square(num) {
return num * num;
}
console.log(square(4)); // Output: 16