JavaScript Functions
- Reusability: Functions can be called multiple times, avoiding repetition of code.
- Modularity: Functions break a large task into smaller, manageable pieces, making code easier to understand.
- Encapsulation: They encapsulate logic, making it isolated and preventing conflicts with other parts of the program.
- Parameters and Arguments: Functions can take parameters (inputs) that allow them to handle different data dynamically.
- Return Values: Functions can return values to the calling code, allowing results to be stored or processed further.
Function Declaration
A function declaration defines a named function. To declare a function, use the function keyword, followed by the name of the function, parentheses (), and a block of code {}.
function hellofunc() {
console.log(“Hello, world!”);
}
Calling a Function
To execute a function, you need to call it by its name followed by parentheses.
hellofunc(); // Output: Hello, world!
Function Parameters
Functions can accept inputs called parameters. Parameters are specified within the parentheses in the function declaration.
function hellofunc(name) {
console.log(“Hello, ” + name + “!”);
}
hellofunc(“Alice”); // Output: Hello, Alice!
hellofunc(“Bob”); // Output: Hello, Bob!
Return Statement
The return statement stops the execution of a function and returns a value from that function.
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Output: 8
Function Scope
Variables declared within a function are local to that function and cannot be accessed from outside the function.
function testScope() {
let localVar = “I’m local!”;
console.log(localVar); // Output: I’m local!
}
testScope();
console.log(localVar); // Error: localVar is not defined
Default Parameters
You can set default values for function parameters.
function hellofunc(name = “stranger”) {
console.log(“Hello, ” + name + “!”);
}
hellofunc(); // Output: Hello, stranger!
hellofunc(“Eve”); // Output: Hello, Eve!
Types of JavaScript Functions
1. Recursive Functions
A recursive function is a function that calls itself during its execution. This technique can be useful for solving problems that can be broken down into smaller, similar problems.
How to Write a Recursive Function
When writing a recursive function, it’s important to define:
1. Base Case: The condition under which the function stops calling itself to prevent infinite recursion.
2. Recursive Case: The part of the function where it calls itself with modified arguments, moving towards the base case.
Example: Factorial
The factorial of a non-negative integer nnn (denoted as n!n!n!) is the product of all positive integers less than or equal to nnn. Factorial can be defined recursively as:
Base Case: N = 0 or N = 1, then factorial(N) = 1.
Recurrence Relation: N > 1, then factorial(N) = N * factorial(N – 1).
Factorial Function
function factorial(n) {
// Base case: if n is 0, return 1
if (n === 0) {
return 1;
}
// Recursive case: n * factorial(n – 1)
return n * factorial(n – 1);
}
console.log(factorial(5)); // Output: 120
2. Function Expression
A function expression defines a function inside an expression. Function expressions can be anonymous (without a name).
const hellofunc = function(name) {
console.log(“Hello, ” + name + “!”);
};
hellofunc(“Charlie”); // Output: Hello, Charlie!
3. Arrow Functions
Arrow functions provide a shorter syntax for writing function expressions. They are always anonymous.
const hellofunc = (name) => {
console.log(“Hello, ” + name + “!”);
};
hellofunc(“Dave”); // Output: Hello, Dave!
If the function has a single parameter, you can omit the parentheses:
const hellofunc = name => {
console.log(“Hello, ” + name + “!”);
};
For a single-line function, you can omit the curly braces and the return keyword:
const add = (a, b) => a + b;
let sum = add(4, 6);
console.log(sum); // Output: 10
4. Rest Parameters
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
function sum(…numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
5. Callback Functions
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function.
function processUserInput(callback) {
let name = prompt(“Please enter your name:”);
callback(name);
}
function hellofunc(name) {
console.log(“Hello, ” + name + “!”);
}
processUserInput(hellofunc);
6. Anonymous Functions
Anonymous functions are functions without a name. They are often used as arguments to other functions.
setTimeout(function() {
console.log(“This message is delayed by 2 seconds.”);
}, 2000);
7. IIFE (Immediately Invoked Function Expression)
An IIFE is a function that runs as soon as it is defined.
(function() {
console.log(“This IIFE runs immediately!”);
})();
8. Higher-Order Functions
A higher-order function is a function that takes another function as an argument or returns a function as a result.
function repeat(operation, num) {
for (let i = 0; i < num; i++) {
operation();
}
}
repeat(() => console.log(“Hello!”), 3);
Output:
Hello!
Hello!
Hello!
9. Closures
A closure is a function that has access to its own scope, the scope of the outer function, and the global scope.
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(“Outer Variable: ” + outerVariable);
console.log(“Inner Variable: ” + innerVariable);
};
}
const newFunction = outerFunction(“outside”);
newFunction(“inside”);
Output
Outer Variable: outside
Inner Variable: inside