Functions
What is a function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you write it once inside a function and call it whenever you need it.
Declaring a function
There are two common ways to create functions in JavaScript:
Function declaration:
JavaScript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Manish")); // "Hello, Manish!"Arrow function (modern syntax):
JavaScript
const greet = (name) => {
return `Hello, ${name}!`;
};For short one-liners, arrow functions can be even more concise:
JavaScript
const greet = (name) => `Hello, ${name}!`;
const double = (n) => n * 2;Both work the same for most cases. Arrow functions are popular in modern JavaScript, especially when passing functions as arguments.
Parameters and return values
Parameters are inputs to the function. Return values are the output:
JavaScript
function add(a, b) {
return a + b;
}
const result = add(3, 7); // result is 10If a function doesn't have a
return statement, it returns undefined.You can also set default parameters:
JavaScript
function greet(name = "stranger") {
return `Hello, ${name}!`;
}
greet(); // "Hello, stranger!"
greet("Manish"); // "Hello, Manish!"Functions as values
In JavaScript, functions are first-class citizens — you can store them in variables, pass them as arguments, and return them from other functions.
This is used everywhere in JavaScript:
JavaScript
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2);
// [2, 4, 6, 8, 10]
const evens = numbers.filter((n) => n % 2 === 0);
// [2, 4]
const sum = numbers.reduce((total, n) => total + n, 0);
// 15map, filter, and reduce each take a function as an argument. This pattern is called higher-order functions, and it's one of JavaScript's most powerful features.Scope
Variables declared inside a function are local to that function:
JavaScript
function sayHello() {
const message = "Hello!";
console.log(message); // Works
}
sayHello();
console.log(message); // Error! message is not defined outsideThis is a good thing — it prevents variables from leaking and colliding with each other.
Key takeaway
Functions are the building blocks of any JavaScript program. Start with function declarations, learn arrow functions, and practice using
map, filter, and reduce — they come up in almost every real project.