A function is a block of code designed to perform a particular task. You can define a function once and call it multiple times.
A function declaration defines a function with a specific name and can be called after it's defined.
// Function declaration
function greet(name) {
console.log('Hello, ' + name);
}
// Calling the function
greet('Shubhadip'); // Output: Hello, Shubhadip
greet
function takes a parameter name
and logs a greeting message.A function expression assigns a function to a variable. The function can be anonymous (without a name) or named.
// Function expression
const add = function(a, b) {
return a + b;
};
// Calling the function
console.log(add(2, 3)); // Output: 5
add
.Arrow functions provide a shorter syntax for writing functions.
// Arrow function
const multiply = (a, b) => a * b;
// Calling the function
console.log(multiply(2, 3)); // Output: 6
this
context, so they behave differently in certain situations.A function can return a value that can be used later.
function square(x) {
return x * x;
}
console.log(square(4)); // Output: 16
return
keyword exits the function and returns a value.