How to Create a Function in JavaScript
Learn the different ways to create functions in JavaScript including function declarations, expressions, and arrow functions.
Functions are reusable blocks of code in JavaScript. Here are the different ways to create them.
Method 1: Function Declaration
The traditional way to define a function:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // "Hello, Alice!"
Method 2: Function Expression
Assign a function to a variable:
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob")); // "Hello, Bob!"
Method 3: Arrow Functions (ES6+)
A shorter syntax for writing functions:
const greet = (name) => {
return "Hello, " + name + "!";
};
// Even shorter for single expressions
const greetShort = (name) => "Hello, " + name + "!";
console.log(greetShort("Charlie")); // "Hello, Charlie!"
Functions with Multiple Parameters
function add(a, b) {
return a + b;
}
// Arrow function version
const multiply = (a, b) => a * b;
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
Default Parameters
function greet(name = "World") {
return "Hello, " + name + "!";
}
console.log(greet()); // "Hello, World!"
console.log(greet("Alice")); // "Hello, Alice!"
Summary
- Use function declarations for hoisted, named functions
- Use function expressions when assigning to variables
- Use arrow functions for concise syntax and callbacks