What Is a Function in JavaScript Beginner Guide
A function is a reusable block of code that performs a specific task. Learn what functions are, why they matter, and how they turn repetitive code into clean, callable logic.
A function is a reusable block of code that does one specific job. You write the code once, give it a name, and then call that name whenever you need the job done. Instead of copying and pasting the same five lines every time, you call the function.
Think of a function like a recipe. The recipe tells you what ingredients to use and what steps to follow, but the recipe itself does not cook anything. You have to follow it. A function is the same: defining it writes the instructions, but calling it actually runs them.
// Define the function (write the recipe)
function greet() {
console.log("Hello there!");
}
// Call the function (follow the recipe)
greet();
greet();
greet();Calling greet three times runs the same two lines of code three times over, so the console prints the same greeting three times in a row. Nothing about the function changes between calls, only the number of times you choose to call it does.
Hello there!
Hello there!
Hello there!Three lines of output from two lines of logic. The function body runs fresh every time you call it. That is the core idea: define once, use many times.
Why Functions Matter
Without functions, every program would be one long flat list of instructions. If you needed to do the same calculation in three places, you would copy the same code three times. When a bug appears, you fix it in three places. When requirements change, you update three places.
Functions solve this by giving logic a name and a home. You write the logic once, and every call site just says "do that thing."
| Without Functions | With Functions |
|---|---|
| Copy-paste the same code everywhere | Write once, call by name |
| Fix bugs in multiple places | Fix once, all callers benefit |
| Hard to tell what code does at a glance | A good function name explains the intent |
| Long flat files | Code organized into named, testable pieces |
This principle has a name: DRY -- Do not Repeat Yourself. Functions are the primary tool for keeping JavaScript code DRY.
Anatomy of a Function
Every function has four parts:
function add(a, b) {
return a + b;
}-
The function keyword -- tells JavaScript you are about to define a function.
-
The name (add) -- what you use to call the function later. Choose names that say what the function does.
-
The parameters (a and b) -- placeholders for values you pass in when calling. They act like local variables inside the function body.
-
The body (the curly-brace block) -- the code that runs every time the function is called.
Calling add with 3 and 4 fills the a and b slots, runs the body, and returns 7.
Parameters and Arguments
Parameters and arguments are easy to confuse because they look like the same thing. They are not.
- Parameters are the names listed in the function definition. They are placeholders.
- Arguments are the actual values you pass when calling the function.
// price and quantity are PARAMETERS (placeholders)
function calculateTotal(price, quantity) {
return price * quantity;
}
// 19.99 and 3 are ARGUMENTS (actual values)
calculateTotal(19.99, 3); // returns 59.97If you want to dig deeper into the distinction, see JS Function Parameters vs Arguments Differences.
Return Values
The return statement does two things: it sends a value back to the caller, and it immediately stops the function.
function double(n) {
return n * 2;
console.log("This line never runs");
}
const result = double(5);
console.log(result);The return line sends the doubled value straight back to the caller, so the function exits before the log statement inside it ever runs. That returned value gets stored in the result variable, and logging it prints:
10The line after return is unreachable. Once return executes, the function exits.
If a function has no return statement, it implicitly returns undefined:
function sayHi() {
console.log("Hi!");
}
const value = sayHi();
console.log(value); // undefinedThis is why a logging call prints to the console but its own return value is always undefined. It does a job but returns nothing.
Functions Are Values
In JavaScript, functions are first-class objects. That means you can treat a function like any other value: assign it to a variable, pass it to another function, or return it from a function.
// Assign a function to a variable
const sayHello = function() {
console.log("Hello!");
};
sayHello(); // Works exactly like a declared functionThe function itself has no name here. It is an anonymous function stored in the sayHello variable. You call it through the variable name.
Because functions are values, you can pass them around:
function runTwice(action) {
action();
action();
}
runTwice(() => console.log("Running!"));The runTwice function receives another function through its action parameter, then calls that parameter twice inside its own body. Each call runs the small arrow function passed in, so the console prints the same line twice:
Running!
Running!This pattern, passing functions as arguments, is the foundation of callbacks and higher-order functions.
Function Declaration vs Expression
JavaScript gives you two common ways to define a function. A function declaration names the function directly:
function multiply(a, b) {
return a * b;
}A function expression instead assigns an unnamed function to a variable, so the variable becomes the way you call it:
const timesTwo = function(a, b) {
return a * b;
};| Style | How it looks | Hoisted |
|---|---|---|
| Function declaration | function multiply(a, b) { ... } | Yes, callable before its line |
| Function expression | const timesTwo = function(a, b) { ... } | No, only after the line runs |
The key difference is hoisting. A function declaration is hoisted, meaning you can call it before the line where it appears in the code. A function expression is not hoisted, the variable exists, but the function is not assigned until the line runs.
// This works (declaration is hoisted)
console.log(double(4)); // 8
function double(n) {
return n * 2;
}
// This fails (expression is not hoisted)
console.log(triple(4)); // ReferenceError
const triple = function(n) {
return n * 3;
};For a full comparison, read JavaScript Function Expressions vs Declarations.
A Quick Look at Arrow Functions
ES6 introduced a shorter syntax called arrow functions. Written as a regular function expression, adding two numbers looks like this:
const addNumbers = function(a, b) {
return a + b;
};The same logic as an arrow function drops the function keyword and the curly braces around a single return statement:
const addNumbers = (a, b) => a + b;Arrow functions are concise and do not have their own this binding, which makes them useful for callbacks and functional patterns.
Common Beginner Mistake: Forgetting to Call the Function
A function definition does nothing on its own. Seeing function greet() in your code does not mean it ran. You must write greet() with parentheses to actually call it.
function greet() {
console.log("Hi!");
}
greet; // Does nothing visible (just references the function)
greet(); // Prints "Hi!" (calls the function)The parentheses are the trigger. Without them, you are just pointing at the function, not running it.
Where to Go Next
A function only does its job once you call it, and it can hand data back through a return value. That is the whole idea. From here, learn how to declare and call functions in each of the three available styles, then explore recursion once calling and returning feel natural.
Rune AI
Key Insights
- A function is a reusable block of code that performs a task when called.
- Functions take input through parameters and can return output with the return keyword.
- Functions keep code DRY (Do not Repeat Yourself) by letting you write logic once and reuse it.
- A function does nothing until it is called. Defining it is not enough.
- Functions are first-class objects in JavaScript, which means they can be assigned to variables, passed around, and returned from other functions.
Frequently Asked Questions
What is the difference between a function and a method?
Do I always need to use the return keyword?
Can a function call another function?
Conclusion
Functions are the building blocks of JavaScript programs. They let you name a block of code, call it whenever you need it, pass data in through parameters, and get results back through return values. Once you understand that a function is just a reusable, callable set of instructions, you are ready to learn how to declare them, pass arguments, and use them to structure real programs.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.