Note: Arrow functions do not have their own
this binding.7. Anonymous Functions
An anonymous function is a function without a name.
setTimeout(function() {
console.log("Hello after 2 seconds");
}, 2000);Output after approximately 2 seconds:
Hello after 2 seconds
Anonymous functions are frequently used as callbacks.
8. Default Parameters
Default parameters provide fallback values when an argument is missing or
undefined.function greet(name = "Guest") {
console.log("Hello " + name);
}
greet("Rahul");
greet();Output:
Hello Rahul
Hello Guest
9. Rest Parameters
Rest parameters allow a function to accept multiple arguments and collect them into an array.
function calculateTotal(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(calculateTotal(10, 20, 30, 40));Output:
100
Here,
...numbers collects all the supplied arguments into one array.10. Callback Functions
A callback is a function passed as an argument to another function.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function message() {
console.log("Welcome to JavaScript");
}
greet("Rahul", message);Output:
Hello Rahul
Welcome to JavaScript
Callbacks are widely used in:
• Event handling.
• Asynchronous programming.
• Array methods.
• API operations.
11. Immediately Invoked Function Expression (IIFE)
An IIFE is a function that executes immediately after it is defined.
(function() {
console.log("Function executed immediately");
})();Output:
Function executed immediately
IIFEs were traditionally used to create private scopes and avoid polluting the global namespace.
12. Function Scope
Scope determines where a variable can be accessed.
JavaScript has different types of scope.
A. Global Scope
Variables declared outside functions and blocks may be accessible throughout their containing script or module environment.
let name = "Rahul";
function greet() {
console.log(name);
}
B. Function Scope
Variables declared with
var inside a function are accessible within that function.function test() {
var age = 25;
console.log(age);
}
test();C. Block Scope
Variables declared using
let and const inside a block are accessible only within that block.if (true) {
let age = 25;
const city = "Delhi";
}
console.log(age); // ReferenceError13. Higher-Order Functions
A higher-order function is a function that accepts another function as an argument or returns a function.
function calculate(a, b, operation) {
return operation(a, b);
}
function add(x, y) {
return x + y;
}
console.log(calculate(10, 20, add));Higher-order functions are widely used in functional programming and array operations.
14. Real-World Example: Employee Salary Calculator
