In JavaScript, a function is a block of code designed to perform a specific task. Functions are executed when they are called or invoked. Functions allow you to reuse code, making your programs more modular and easier to manage.
1. Syntax of a Function:
function functionName(parameters) {
// Code to be executed
}
Explanation:
functionName: The name of the function.parameters: Values passed to the function when it is called.return: (Optional) Returns a value from the function.
2. Creating and Calling a Function:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!
Explanation:
- The
greetfunction takes anameas a parameter and returns a greeting message. - The function is called with
"Alice"as an argument.
3. Function with Multiple Parameters:
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(5, 10)); // Output: 15
Explanation:
- The
addNumbersfunction takes two parameters,aandb, and returns their sum.
4. Function Without Parameters:
function sayHello() {
return "Hello, World!";
}
console.log(sayHello()); // Output: Hello, World!
Explanation:
- The
sayHellofunction does not take any parameters and simply returns a fixed greeting message.
5. Function Expressions:
A function expression is a function that is assigned to a variable.
let greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob")); // Output: Hello, Bob!
Explanation:
- The function is assigned to the variable
greetand can be invoked using that variable.
6. Arrow Functions:
Arrow functions provide a shorter syntax for writing functions.
let greet = (name) => "Hello, " + name + "!";
console.log(greet("Charlie")); // Output: Hello, Charlie!
Explanation:
- Arrow functions use the
=>syntax and can omit thereturnkeyword for concise expressions.
7. Anonymous Functions:
Anonymous functions are functions without a name, often used as arguments to other functions.
setTimeout(function() {
console.log("This message is delayed by 2 seconds.");
}, 2000);
Explanation:
- The anonymous function is executed after a 2-second delay using
setTimeout.
8. Immediately Invoked Function Expressions (IIFE):
An IIFE is a function that is executed immediately after it is defined.
(function() {
console.log("This function runs immediately!");
})();
Explanation:
- The function is defined and immediately invoked, allowing code to execute right away.
9. Functions as Arguments:
Functions can be passed as arguments to other functions.
function processUserInput(callback) {
let name = prompt("Please enter your name:");
callback(name);
}
processUserInput(function(name) {
alert("Hello, " + name + "!");
});
Explanation:
- The
processUserInputfunction takes another function (callback) as an argument and calls it with the user’s input.
10. Function Scope:
Variables defined inside a function are local to that function.
function testScope() {
let localVar = "I'm local!";
console.log(localVar);
}
testScope(); // Output: I'm local!
// console.log(localVar); // Error: localVar is not defined
Explanation:
localVaris accessible only insidetestScope.
11. Default Parameters:
You can provide default values for function parameters.
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet()); // Output: Hello, Guest!
Explanation:
- If no argument is provided,
namedefaults to"Guest".
12. Rest Parameters:
Rest parameters allow a function to accept an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Explanation:
- The
sumfunction uses the rest parameter...numbersto collect all arguments into an array and calculates their sum.
Conclusion:
- Functions are a fundamental building block in JavaScript, enabling modular, reusable, and maintainable code.
- Understanding different types of functions, their syntax, and behavior helps in writing efficient JavaScript code.