Functions in JavaScript
Here’s a comprehensive guide to Functions in JavaScript with examples:
1. What is a Function?
A function is a block of reusable code designed to perform a particular task. It is executed when it is invoked or called.
Syntax:
function functionName(parameters) {
// Code to execute
}
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // Output: Hello, Alice!
2. Types of Functions in JavaScript
A. Function Declaration
A function declared using the function
keyword.
Example:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Output: 5
B. Function Expression
Functions can also be stored in variables.
Example:
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(2, 3)); // Output: 6
C. Arrow Functions (ES6)
A concise syntax for writing functions.
Syntax:
const functionName = (parameters) => {
// Code to execute
};
Example:
const subtract = (a, b) => a - b;
console.log(subtract(5, 3)); // Output: 2
D. Anonymous Functions
Functions without a name, often used as callbacks.
Example:
setTimeout(function () {
console.log("This runs after 2 seconds");
}, 2000);
E. Immediately Invoked Function Expression (IIFE)
A function that runs immediately after it is defined.
Example:
(function () {
console.log("IIFE is executed immediately!");
})();
3. Parameters and Arguments
- Parameters: Variables defined in the function definition.
- Arguments: Values passed when calling the function.
Example:
function greet(name, age) {
console.log(`Hi ${name}, you are ${age} years old.`);
}
greet("Bob", 25); // Output: Hi Bob, you are 25 years old.
4. Default Parameters
Provide default values for parameters if no argument is passed.
Example:
function sayHello(name = "Guest") {
console.log(`Hello, ${name}!`);
}
sayHello(); // Output: Hello, Guest!
5. Rest Parameters
Used to handle 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
6. Return Statement
Functions can return a value using the return
statement.
Example:
function square(num) {
return num * num;
}
console.log(square(4)); // Output: 16
7. Callback Functions
A function passed as an argument to another function and executed later.
Example:
function processUserInput(callback) {
const name = "Charlie";
callback(name);
}
processUserInput((name) => {
console.log(`Hello, ${name}!`);
});
// Output: Hello, Charlie!
8. Higher-Order Functions
Functions that accept other functions as arguments or return functions.
Example:
function applyOperation(a, b, operation) {
return operation(a, b);
}
const add = (x, y) => x + y;
const multiply = (x, y) => x * y;
console.log(applyOperation(3, 4, add)); // Output: 7
console.log(applyOperation(3, 4, multiply)); // Output: 12
9. Closures
A closure is a function that remembers its outer variables even after the outer function has finished executing.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const myFunction = outerFunction("Outside");
myFunction("Inside");
// Output: Outer: Outside, Inner: Inside
10. Function Scope
Functions have their own local scope.
Example:
function showMessage() {
let message = "Hello, World!";
console.log(message);
}
showMessage();
// console.log(message); // Error: message is not defined
11. Recursion
A function that calls itself.
Example:
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
12. Pure Functions
A pure function produces the same output for the same input and has no side effects.
Example:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Output: 5
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
Top comments (0)