Functions are one of JavaScript's most fundamental building blocks. They allow us to encapsulate a block of code that performs a specific task, making your code modular, reusable, and easier to maintain.
Types of Functions in JavaScript
Function Declaration
A standard way to define a function. It is hoisted, meaning it can be called before its declaration in the code.Syntax:
function functionName(parameters) { // Function body }
Example:
function greet(name) { return `Hello, ${name}!`; } console.log(greet("Hridoy")); // Output: Hello, Hridoy!
Function Expression
Functions can also be assigned to variables. These are not hoisted.Syntax:
const functionName = function(parameters) { // Function body };
Example:
const multiply = function(a, b) { return a * b; }; console.log(multiply(3, 4)); // Output: 12
Arrow Functions
Introduced in ES6, they provide a shorter syntax for writing functions. They do not have their ownthis
context.Syntax:
const functionName = (parameters) => expression;
If the function body has a single expression,
{}
andreturn
can be omitted.For multiple statements, use
{}
and explicitly writereturn
if needed.
Examples:
Single Expression:
const square = (x) => x * x;
console.log(square(4)); // Output: 16
Multiple Statements:
const greet = (name) => {
const message = `Hello, ${name}!`;
return message;
};
console.log(greet("Hridoy")); // Output: Hello, Hridoy!
Callback Example:
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // Output: [2, 4, 6]
When to Use Arrow Functions
When we need concise syntax for short functions.
For callbacks, such as in array methods (
map
,filter
).When we want
this
to refer to the outer scope.
Parameters and Arguments
Parameters are placeholders defined in the function declaration.
Arguments are the actual values passed when calling the function.
Example:
function subtract(a, b) { return a - b; } console.log(subtract(10, 5)); // Output: 5
Default Parameters
Default parameters in JavaScript functions provide flexibility by allowing parameters to have default values when no argument or undefined
is passed during function invocation. Let's explore different cases of how default parameters behave:
Basic Case
If a function argument is omitted or passed as
undefined
, the default value is used.function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } greet('Anuj'); // Output: Hello, Anuj! greet(); // Output: Hello, Guest!
Explanation:
In the first call,
'Anuj'
is passed, so'Guest'
is not used.In the second call, no argument is passed, so the default
'Guest'
is used.
Passing
undefined
When
undefined
is explicitly passed, the default parameter value is still used.function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } greet(undefined); // Output: Hello, Guest!
Explanation:
- Even though
undefined
is passed, the function still uses the default value'Guest'
.
- Even though
Passing
null
Passing
null
does not trigger the default value becausenull
is considered a valid value.function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } greet(null); // Output: Hello, null!
Explanation:
null
is explicitly passed, so it is treated as a value and replaces the default value'Guest'
.
Array as a Parameter
We can pass arrays as parameters and even set default values for arrays.
function joinArray(arr = ["default", "values"], separator = " ") { return arr.join(separator); } console.log(joinArray(["apple", "banana", "cherry"], "-")); // Output: apple-banana-cherry console.log(joinArray()); // Output: default values
Explanation:
- If no array is passed, the function uses the default array
["default", "values"]
. You can also set a custom separator forjoin()
.
- If no array is passed, the function uses the default array
Object as a Parameter
Objects can be passed as parameters, and you can use destructuring to extract values. You can also set default values for object properties.
function displayUser({ name = "Guest", age = 18, city = "Unknown" } = {}) { console.log(`Name: ${name}, Age: ${age}, City: ${city}`); } displayUser({ name: "Anuj", age: 25, city: "Delhi" }); // Output: Name: Anuj, Age: 25, City: Delhi displayUser({ name: "Hridoy" }); // Output: Name: Hridoy, Age: 18, City: Unknown displayUser(); // Output: Name: Guest, Age: 18, City: Unknown
Explanation:
- If no object is passed or an object with missing properties is passed, default values are assigned to
name
,age
, andcity
.
- If no object is passed or an object with missing properties is passed, default values are assigned to
Rest Parameters
Allows a function to accept an indefinite number of arguments as an array.
Example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Anonymous Functions
These are functions without a name, often used in callbacks or event listeners.
Example:
setTimeout(function() {
console.log("Anonymous Function Executed!");
}, 1000);
Functions are the backbone of JavaScript programming, enabling dynamic and efficient code. Mastering them is essential for any developer.