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.
Rest and spread parameters
Collect remaining arguments with rest syntax:
JavaScript
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
sum(1, 2, 3, 4); // 10Spread passes array elements as individual arguments:
JavaScript
const nums = [3, 7];
Math.max(...nums); // 7Rest and spread use the same
... syntax in different positions — rest gathers values into an array, spread expands an array into values.Arrow functions and this
Arrow functions don't have their own
this — they inherit this from the surrounding scope. That makes them ideal for callbacks inside methods when you want lexical this. For object methods that need their own this, use regular function syntax:JavaScript
const counter = {
count: 0,
increment() {
setInterval(() => {
this.count += 1; // arrow inherits counter's this
}, 1000);
},
};You'll revisit
this in depth when working with classes and DOM event handlers.Pure functions and side effects
A pure function returns the same output for the same input and doesn't mutate external state. Pure functions are easier to test and reason about:
JavaScript
function doubleAll(numbers) {
return numbers.map((n) => n * 2); // returns new array, doesn't mutate input
}Impure functions (logging, DOM updates, network calls) are necessary in apps — but isolating pure logic in small functions keeps code maintainable.
Choosing function syntax
Use a function declaration when you want a named function that is hoisted — available anywhere in its scope, even above the line where it is written. That is helpful for utility functions and recursive helpers. Use an arrow function for short callbacks passed to
map, filter, event listeners, and timers. When a function grows beyond a few lines or needs its own this binding (for example, as a method on an object), a regular function is usually clearer.Break large functions into smaller ones. If a function does three distinct things, extract each part into a named helper. Readable function names act as documentation:
formatCurrency(total) tells readers more than a block of arithmetic inline.Parameters, arguments, and return values
Arguments you pass to a function are copies of references for objects and arrays — reassigning a parameter does not change the outer variable, but mutating an object property inside the function does affect the original object. Return values are how functions communicate results back to callers. Prefer returning data over mutating global variables; it makes data flow easier to follow and test.
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.