JavaScript Functions Explained for Beginners

Functions let you package up a block of code and reuse it whenever you need it, instead of retyping the same logic over and over. This guide covers how to define, call, and return values from JavaScript functions.

If you’ve followed our guides on connecting JavaScript to HTML and variables, you’re ready for one of the most fundamental building blocks in the language: functions. Nearly everything you’ll write from here on out — from small scripts to full applications — is built out of functions calling other functions.

This guide covers what a function actually is, how to define and call one, how parameters and return values work, and the shorter arrow function syntax you’ll see constantly in modern JavaScript code.

What a Function Actually Is

According to MDN’s guide to JavaScript functions, functions allow you to store a piece of code that performs a single task inside a defined block, then call that code whenever you need it using a short command — rather than typing out the same logic repeatedly throughout your program.

Here’s the simplest possible function:

function greet() {
  console.log("Hello!");
}

greet(); // calls the function, printing "Hello!"

Defining a function (the first block) doesn’t run its code — it just stores the instructions under the name greet. The code only actually runs when you call the function, using its name followed by parentheses: greet().

Parameters and Arguments

Most useful functions accept input, so they can behave differently depending on what’s passed to them. These inputs are called parameters when you define the function, and arguments when you actually call it:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Alex"); // Hello, Alex!
greet("Sam");  // Hello, Sam!

Here, name is the parameter — a placeholder that stands in for whatever value gets passed in. "Alex" and "Sam" are the arguments — the actual values supplied each time the function is called. As freeCodeCamp’s guide to JavaScript functions puts it, this distinction trips up a lot of beginners at first, but it’s simply describing the same value from two different perspectives: the placeholder versus the real thing passed in.

Returning a Value

So far, our example functions have only printed something to the console. Often, you want a function to calculate a value and hand it back to whatever called it, rather than just printing it. That’s what the return keyword does:

function add(a, b) {
  return a + b;
}

const result = add(5, 3);
console.log(result); // 8

According to W3Schools’ introduction to JavaScript functions, functions let the same block of code produce different results depending on the input — the add function above works identically no matter which two numbers you pass it, producing a different result each time based purely on its arguments.

Once a return statement runs, the function stops immediately — any code written after it inside the same function never executes. This is a useful detail to remember once your functions get slightly more complex.

Function Declarations vs. Arrow Functions

Everything above used the function keyword — this style is called a function declaration. Modern JavaScript also supports a shorter syntax called an arrow function, which you’ll see constantly in real-world code:

// Function declaration
function add(a, b) {
  return a + b;
}

// Arrow function, equivalent behavior
const add = (a, b) => {
  return a + b;
};

// Arrow function, shortened further (single expression)
const add = (a, b) => a + b;

When an arrow function’s body is a single expression, you can drop the curly braces and the return keyword entirely — the result of that expression is returned automatically. This shorthand is optional, but it’s extremely common in JavaScript you’ll encounter online, so it’s worth recognizing even before you start using it yourself.

A Practical Example

Here’s a slightly larger example that combines a function with a loop, tying together concepts from earlier in this series:

function double(number) {
  return number * 2;
}

const numbers = [1, 2, 3, 4];

for (const num of numbers) {
  console.log(double(num));
}

This defines a small, reusable function that doubles whatever number it’s given, then calls it once for each item in a list — a genuinely common pattern once you start combining functions with loops.

Function Scope: What a Function Can and Can’t See

Variables created inside a function only exist inside that function — this is called scope. Once the function finishes running, those variables disappear, and code outside the function has no way to access them:

function calculateTotal() {
  const tax = 0.08;
  return 100 * (1 + tax);
}

console.log(tax); // ReferenceError: tax is not defined

This isn’t a limitation to work around — it’s a genuinely useful feature. Keeping a function’s internal variables contained means you don’t have to worry about accidentally overwriting a variable somewhere else in a large program just because you happened to reuse a common name like total or count inside a function.

The reverse direction works differently: a function can read variables that exist outside it, in the surrounding scope, as long as those variables were declared before the function is called:

const taxRate = 0.08;

function calculateTotal(price) {
  return price * (1 + taxRate); // reads taxRate from outside
}

console.log(calculateTotal(100)); // 108

Default Parameter Values

Sometimes you want a parameter to have a sensible fallback value if the function is called without providing one. Modern JavaScript lets you define this directly in the function’s parameter list:

function greet(name = "friend") {
  console.log(`Hello, ${name}!`);
}

greet("Alex"); // Hello, Alex!
greet();       // Hello, friend!

Without a default value, calling greet() with no argument would print “Hello, undefined!” instead — default parameters are a small, clean way to avoid that kind of awkward output without adding extra conditional checks inside the function body.

Naming Functions Well

A small habit that pays off quickly: name functions after what they do, usually starting with a verb — calculateTotal, greetUser, isValidEmail. A well-named function often makes comments unnecessary, since reading double(number) tells you exactly what to expect without needing to look at the implementation at all. This becomes increasingly valuable as your programs grow and you start calling functions written days or weeks earlier.

Common Questions Beginners Ask About Functions

Do all functions need to return a value? No. A function that doesn’t include a return statement simply returns undefined by default, which is perfectly fine for functions whose whole purpose is an action (like printing something), rather than producing a value.

What if I call a function with the wrong number of arguments? JavaScript doesn’t enforce the number of arguments — a missing argument simply becomes undefined inside the function, which can lead to confusing bugs if you’re not careful. This is different from many other languages, which raise an error immediately.

Should I always use arrow functions instead of the function keyword? Not necessarily — both are valid and widely used. As a beginner, it’s more important to understand what each does than to pick one style dogmatically; you’ll naturally develop a preference as you read more real-world code.

Can a function call itself? Yes — this is called recursion, and it’s a genuinely powerful technique for certain kinds of problems, though it’s worth treating as an advanced topic to revisit once basic functions feel completely comfortable. Most everyday tasks don’t require it.

What’s the difference between a function and a method? They’re the same concept, just named differently based on context — a method is simply a function that belongs to an object. You’ll encounter this distinction more once you start working with objects directly.

Quick-Reference JavaScript Functions Guide

  • Defining a function — stores the code; it doesn’t run until called.
  • Calling a function — runs its code, using the function’s name followed by parentheses.
  • Parameters — placeholders defined with the function.
  • Arguments — actual values passed in when calling the function.
  • return — sends a value back and immediately stops the function.
  • Arrow functions — a shorter, increasingly common syntax for writing functions.

Conclusion

Functions are the tool that turns repetitive code into something reusable, and understanding parameters, arguments, and return values covers the overwhelming majority of what you’ll need for a long time. Whether you write them with the function keyword or as arrow functions, the underlying idea stays the same: package up a task, give it a name, and call it whenever you need that task done, without retyping the same logic in a dozen different places.

The best way to build real comfort here is writing a handful of small functions yourself — something that adds two numbers, something that greets a name, something that doubles a value — rather than only reading through the examples above and assuming the concepts have fully clicked.

In the next guide in this series, we’ll cover JavaScript arrays — how to store and work with collections of values, which pair naturally and frequently with the functions and loops covered so far in this series.

Explore More JavaScript Basics Guides →

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top