JavaScript Functions: Writing Reusable Code
This post introduces JavaScript functions from the ground up, covering how to define and call functions, use parameters and return values, and write cleaner code using arrow functions and default parameters. It emphasizes the DRY principle and single-responsibility thinking to help beginners write
Functions are one of the most powerful concepts in JavaScript. Once you understand them, you will stop writing the same code over and over again and start building programs that are clean, organized, and easy to maintain. Think of a function as a reusable recipe: you define it once, and you can run it as many times as you need.
What Is a Function?
A function is a named block of code that performs a specific task. Instead of repeating logic throughout your program, you wrap it in a function and call it whenever you need it. This principle is sometimes called DRY (Don't Repeat Yourself), and functions are the primary tool for achieving it.
Here is the simplest possible function in JavaScript:
function greet() {
console.log("Hello, world!");
}
greet(); // Output: Hello, world!
The keyword function tells JavaScript you are defining a function. The name greet is how you will call it later. The parentheses hold any inputs (more on that in a moment), and the curly braces wrap the code that runs when the function is called.
Parameters and Arguments
Functions become much more useful when you pass data into them. The variables listed inside the parentheses during definition are called parameters. The actual values you pass when calling the function are called arguments.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
You can define multiple parameters by separating them with commas:
function add(a, b) {
console.log(a + b);
}
add(3, 5); // Output: 8
add(10, 20); // Output: 30
Return Values
So far, our functions have printed output directly. But often you want a function to return a value that you can store or use elsewhere. That is what the return keyword is for:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 7);
console.log(result); // Output: 28
Once a function hits a return statement, it stops executing and sends that value back to wherever the function was called. This is critical because it lets you chain logic together rather than relying on side effects like console.log.
Function Expressions and Arrow Functions
JavaScript gives you a couple of other ways to write functions. A function expression stores a function inside a variable:
const square = function(n) {
return n * n;
};
console.log(square(6)); // Output: 36
An arrow function is a shorter syntax introduced in modern JavaScript (ES6). It is especially common in code you will see in the wild:
const square = (n) => {
return n * n;
};
// Even shorter for single expressions:
const square = (n) => n * n;
console.log(square(6)); // Output: 36
Arrow functions behave slightly differently with the this keyword in more advanced scenarios, but for basic use cases they work the same as regular functions.
Default Parameters
You can give parameters a fallback value in case no argument is passed:
function greet(name = "stranger") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet(); // Output: Hello, stranger!
This makes your functions more resilient and reduces the need for extra error-checking logic.
Why Functions Matter
Beyond avoiding repetition, functions help you break a large problem into smaller, manageable pieces. Each function should ideally do one thing well. A function called calculateTax should calculate tax, not also format the output and save a file. This single-responsibility principle makes your code easier to read, test, and debug.
What's Next
Now that you understand how to write and call functions, the next step is understanding scope: where variables are accessible and where they are not. Scope and functions are closely connected in JavaScript, and understanding how they interact will help you avoid some of the most common bugs beginners encounter. We will cover that in the next post in this series.
Resources
- MDN Web Docs: Functions: the definitive reference for JavaScript functions with detailed examples.
- JavaScript.info: Function Basics: a beginner-friendly walkthrough with interactive exercises.
- freeCodeCamp: JavaScript Algorithms and Data Structures: free hands-on curriculum covering functions and beyond.