In JavaScript, user-defined functions are functions that you create to perform specific tasks.
They allow you to encapsulate reusable blocks of code, making your program more modular
and easier to read. Here's how to create and use user-defined functions in JavaScript.
1. Function Declaration
This is the most common way to define a function.
function greet(name) {
return `Hello, ${name}!`;
}
// Usage
console.log(greet("Alice")); // Output: Hello, Alice!
In this example:
greet is the function name.
name is a parameter that the function takes.
The function returns a string greeting with the provided name.
2. Function Expression
A function can also be created as a function expression. This assigns a function to a
variable.
const greet = function(name) {
return `Hello, ${name}!`;
};
// Usage
console.log(greet("Bob")); // Output: Hello, Bob!
3. Arrow Function
Introduced in ES6, arrow functions provide a shorter syntax, especially useful for simple
functions.
const greet = (name) => `Hello, ${name}!`;
// Usage
console.log(greet("Charlie")); // Output: Hello, Charlie!
If the function has a single statement and returns a value, you can omit the {} and return
keyword, as shown above.
4. Function with Multiple Parameters
You can add more parameters to a function as needed.
function add(a, b) {
return a + b;
}
console.log(add(3, 5)); // Output: 8
5. Default Parameters
JavaScript functions can also have default parameter values.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet("Diana")); // Output: Hello, Diana!
6. Anonymous Functions
An anonymous function doesn’t have a name. It's commonly used in situations where a
function is used as a value, like in event handlers or as arguments.
setTimeout(function() {
console.log("This message appears after 2 seconds");
}, 2000);
7. Higher-Order Functions
Functions that accept other functions as parameters or return functions are known as
higher-order functions. This is common in functional programming.
function repeat(action, times) {
for (let i = 0; i < times; i++) {
action();
}
}
repeat(() => console.log("Hello!"), 3);
// Output:
// Hello!
// Hello!
// Hello!
By creating user-defined functions, you can encapsulate logic, making your code more
organized, reusable, and easier to maintain.