FunctionsFunctions in JavaScript are blocks of code that can be called to perform a specific task. They help to organize code, reduce redundancy, and make programs easier to maintain.
A Function Declaration defines a named function that can be called anywhere in the code.
function functionName(parameters) {
// code block
}
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
A Function Expression is a function that is defined within an expression, such as a variable assignment.
const functionName = function(parameters) {
// code block
};
const multiply = function(a, b) {
return a * b;
};
let result = multiply(5, 3);
console.log(result); // Output: 15
An Arrow Function provides a shorter syntax for writing functions and doesn't have its own this.
const functionName = (parameters) => {
// code block
};
const subtract = (a, b) => {
return a - b;
};
let result = subtract(5, 3);
console.log(result); // Output: 2
Function Declarations, Function Expressions, and Arrow Functions. Choose the type that best suits your needs based on the use case.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!