Skip to content
beginner

Introduction to Functions

Copying and pasting the same code over and over works for a while—until you need to change something and suddenly have to hunt through ten copies of the…

Published 2026-09-06Updated 2026-09-127 min read
A vibrant green forest with tall trees and sunlit canopy, showcasing nature's beauty.
A vibrant green forest with tall trees and sunlit canopy, showcasing nature's beauty. Photo by Quang Nguyen Vinh on Pexels.

Copying and pasting the same code over and over works for a while—until you need to change something and suddenly have to hunt through ten copies of the same logic. Miss one spot, and your program behaves differently in different places.

JavaScript functions are the cure for that pain. A function is a named, reusable block of code that performs a specific task. Write it once, call it by name whenever you need it, and your code stays organized, readable, and easy to fix.

Think of a function like a recipe. You write the steps down once, give the recipe a name, and any time you want that dish, you pull out the recipe and follow it. You don't rewrite the steps from scratch every time you cook.

Why Functions Exist

When you're first learning to code, it's tempting to write one long script that does everything from top to bottom. You've already seen loops that repeat actions and variables that store values. But what happens when you need the same calculation in three different places?

Without functions, you copy the code. Then you need to change the calculation, and you have to find every copy and update it. Miss one, and your program behaves differently in different spots. That's a debugging nightmare.

Functions solve this by giving you a single place to define a behavior. You write the code once inside a function, give it a name, and then call that function whenever you need it. Change the function's code once, and every call to that function uses the new version.

Functions also make your code easier to read. A well-named function like calculateTotal or validateEmail tells you what a block of code does without you having to trace through every line.

Knowledge check

Check your understanding

Answer this question before you continue.

Why does defining a behavior in one function make later changes easier?
Single Choice

Focus: Explain how functions reduce duplicated code and simplify updates.

Anatomy of a Function Declaration

Let's look at a real JavaScript function. Here's a simple one that greets a user:

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

Let's break down each part:

  • function is the keyword that tells JavaScript you're defining a function.
  • greetUser is the function's name. You choose this, just like a variable name.
  • () are the parentheses. Right now they're empty, but soon they'll hold inputs.
  • { } are the curly braces. Everything between them is the function's body—the code that runs when the function is called.

Here's the key thing to understand: defining a function does not run it yet. The code inside the curly braces is just sitting there, waiting. Nothing happens until you call the function.

Knowledge check

Check your understanding

Answer this question before you continue.

What happens when JavaScript reads this declaration by itself?
Misconception Check

Focus: Distinguish defining a function from calling it.

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

Calling a Function

To actually run the code inside a function, you call it by writing its name followed by parentheses:

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

greetUser();
greetUser();
Hello there!
Hello there!

Each time you write greetUser(), JavaScript executes the function's body. Call it twice, and you get the greeting twice. That's the power of reuse: you wrote the console.log line once, but you can trigger it as many times as you want.

A common beginner mistake is forgetting the parentheses. If you write just greetUser without the (), JavaScript doesn't run the function. It just looks at the function itself, like reading a recipe card without cooking anything. The parentheses are what say, "Run this now."

Common mistake: Defining a function but never calling it. If you run your script and nothing happens, check that you actually wrote functionName() somewhere after the definition.

Knowledge check

Check your understanding

Answer this question before you continue.

What output does this code produce?
Output Prediction

Focus: Predict the output produced by calling a function multiple times.

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

greetUser();
greetUser();

Parameters and Arguments

A function that always prints the same greeting is useful, but limited. What if you want to greet different people by name? That's where parameters and arguments come in.

Parameters are placeholders listed inside the parentheses when you define the function. Arguments are the actual values you pass when you call it.

function greetUser(name) {
  console.log("Hello, " + name + "!");
}

greetUser("Maya");
greetUser("Diego");
Hello, Maya!
Hello, Diego!

In this example, name is a parameter—a placeholder that stands in for whatever value gets passed. When you call greetUser("Maya"), the string "Maya" is the argument, and inside the function, name becomes "Maya".

You can have multiple parameters too, separated by commas:

function greetUser(firstName, lastName) {
  console.log("Hello, " + firstName + " " + lastName + "!");
}

greetUser("Maya", "Chen");
Hello, Maya Chen!

The same function now works for any name you give it. One function, many possible outputs.

Knowledge check

Check your understanding

Answer this question before you continue.

In this code, which statement correctly identifies `name` and `"Maya"`?
Single Choice

Focus: Identify the parameter in a function declaration and the argument supplied by a call.

function greetUser(name) {
  console.log("Hello, " + name + "!");
}

greetUser("Maya");

Return Values

A left-to-right flow shows code calling doubleNumber with 7, the argument 7 entering the number parameter, the function calculating number times 2, and the returned value 14 flowing back to the result variable.
Follow an argument into a function and see how the returned value comes back to the calling code.

So far, our functions have been printing messages to the console. But sometimes you want a function to hand a value back to the code that called it, so you can store that value in a variable or use it in another calculation.

That's what the return keyword does. It sends a value back to the caller.

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

let result = doubleNumber(7);
console.log(result);
14

Here's what's happening step by step:

  1. doubleNumber(7) calls the function with 7 as the argument.
  2. Inside the function, number becomes 7.
  3. The return statement calculates 7 * 2 and sends 14 back.
  4. The returned value gets stored in the result variable.
  5. console.log(result) prints 14.

The difference between printing and returning matters. A function that uses console.log shows output on the screen, but it doesn't give you anything you can use in your code. A function that uses return hands back a value you can store, compare, or pass to another function.

Common mistake: Expecting a function without return to hand back a value. If you don't include return, the function returns undefined—even if it printed something to the console.

Where Functions Show Up in Real Web Projects

These small examples might feel far from a real website, but functions are the building blocks behind almost everything interactive on the web.

In a real project, you might write a function that calculates the total price of an order including tax:

function calculateTotal(price, taxRate) {
  return price + (price * taxRate);
}

Or a function that checks whether a form field has been filled in:

function validateField(value) {
  if (value === "") {
    return "This field is required.";
  }
  return "";
}

Or a function that builds a personalized greeting for a logged-in user:

function buildWelcomeMessage(username) {
  return "Welcome back, " + username + "!";
}

When a user clicks a button, submits a form, or triggers any action on a page, the browser calls a function to respond. Those functions might update text on the page, validate input, fetch data, or change what the user sees. That connection between user actions and functions is called an event, and it's the natural next step after you're comfortable with functions themselves.

Common Beginner Mistakes

Every programmer makes these mistakes. Here's how to spot and fix them quickly.

Forgetting the parentheses when calling a function.

// Wrong: this doesn't run the function
greetUser;

// Right: this runs it
greetUser();

Without the parentheses, you're just referring to the function itself, not executing it.

Defining a function but never calling it.

If you write a function and run your script, but nothing appears in the console, check that you actually called the function. Defining it is only half the job.

Expecting a value from a function without return.

function add(a, b) {
  let sum = a + b;
  // No return statement here!
}

let result = add(3, 4);
console.log(result); // undefined

If you need the result, include return. If you only need to display something, console.log inside the function is fine.

Your Turn

The best way to make functions click is to write a few yourself. Open your browser's console (press F12 and look for the Console tab) and try this:

  1. Write a function called greet that takes a name parameter and prints a greeting.
  2. Write a function called doubleNumber that takes a number and returns it doubled.
  3. Call each function at least twice with different arguments.

Here's a starting point:

function greet(name) {
  console.log("Hi, " + name + "!");
}

greet("Sam");
Hi, Sam!

Once you're comfortable defining and calling functions, you're ready for the next step: making your web pages respond to what users actually do. That's where events come in—the clicks, keystrokes, and form submissions that trigger your functions in the browser.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

What does this code print?
Question 1 of 2Output Prediction

Focus: Trace a returned value into a variable and predict the resulting output.

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

let result = doubleNumber(7);
console.log(result);
What change is needed for `result` to contain the sum instead of `undefined`?
Question 2 of 2Debugging

Focus: Recognize when a function needs `return` to provide a reusable value.

function add(a, b) {
  let sum = a + b;
  // No return statement here!
}

let result = add(3, 4);

References

  1. Functions - JavaScript - MDN Web Docsdeveloper.mozilla.org
  2. Functions  |  web.devweb.dev
8sources checked
8source domains
5searches run

Research updated Sep 6, 2026

Keep learning

Related tutorials

Continue with nearby JavaScript topics and beginner-friendly explanations.

A breathtaking view of a tropical sunset with vibrant colors reflecting on the calm sea.
beginner
7 min read

Arrow Functions Basics

JavaScript arrow functions let you write the same functions you already know in fewer lines. The idea isn't new—only the syntax is shorter.

Read tutorial