← Back to course

Functions

Functions

Welcome back.

In the previous lesson, you taught JavaScript how to make decisions.

JavaScript learned if, else, comparison operators, and logical operators.

Very powerful.

Slightly dangerous.

Today we teach JavaScript how to reuse code.

That means we are learning functions.

Functions are one of the most important ideas in programming.

A function is a reusable block of code.

Instead of writing the same code again and again, you write it once, give it a name, and call it when you need it.

Without functions, your code becomes copy-paste soup.

With functions, your code becomes cleaner, easier to understand, and less likely to attack you at 2 AM.

Very important.

Your future self is already preparing to thank you.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, you will be able to organize JavaScript code into reusable pieces.

This is a major step.

Variables remember values.

Conditions make decisions.

Functions create actions you can reuse.

JavaScript is slowly becoming a civilized creature.

Mostly.

What Is a Function?

A function is a named block of code.

Example:

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

This creates a function named sayHello.

But creating a function does not run it.

To run it, you must call it:

sayHello();

Full example:

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

sayHello();

Output:

Hello!

Think of a function like a machine.

You build the machine once.

Then you press the button whenever you want it to work.

Very useful.

Especially if the machine does not explode.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson4
cd javascript-lesson4
touch index.html
touch script.js

Your project should look like this:

javascript-lesson4/
  index.html
  script.js

Open the folder in your editor.

We will start in the console.

Then we will use functions to update a web page.

Simple.

Clean.

No framework dragon today.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Functions</title>
</head>
<body>
  <h1>Functions</h1>
  <p>Open the browser console to see JavaScript output.</p>

  <script src="script.js"></script>
</body>
</html>

Open the file in your browser.

Open the console:

Now JavaScript is ready.

The console is watching.

Again.

Your First Function

Open script.js and add:

function greetUser() {
  console.log("Welcome to JavaScript!");
}

greetUser();

Refresh the browser.

You should see:

Welcome to JavaScript!

What happened?

function greetUser() {
  console.log("Welcome to JavaScript!");
}

This defines the function.

greetUser();

This calls the function.

A function does not run until you call it.

This is important.

Writing a function is like writing a recipe.

Calling a function is like actually cooking.

If you only write the recipe, nobody eats.

Sad.

But organized.

Calling a Function Multiple Times

You can call the same function more than once.

function greetUser() {
  console.log("Welcome to JavaScript!");
}

greetUser();
greetUser();
greetUser();

Output:

Welcome to JavaScript!
Welcome to JavaScript!
Welcome to JavaScript!

The code inside the function runs every time you call it.

This is the power of functions.

Write once.

Use many times.

Less copy-paste.

Less chaos.

More dignity.

Why Functions Are Useful

Without a function:

console.log("Welcome, Anna!");
console.log("Welcome, Marco!");
console.log("Welcome, Viktor!");

This works.

But imagine doing this in many places.

Now with a function:

function welcomeUser(name) {
  console.log(`Welcome, ${name}!`);
}

welcomeUser("Anna");
welcomeUser("Marco");
welcomeUser("Viktor");

Much better.

The function contains the logic.

The name changes.

The structure stays the same.

This is how programmers avoid repeating themselves.

Because repetition is fine in exercise.

But in code, repetition eventually becomes a small monster wearing a hoodie.

Parameters and Arguments

A parameter is a variable inside a function.

An argument is the actual value you pass into the function.

Example:

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

greet("Anna");

Here:

When you call:

greet("Anna");

JavaScript puts "Anna" into name.

Then the function uses it.

Another example:

function showAge(age) {
  console.log(`You are ${age} years old.`);
}

showAge(33);
showAge(25);

Output:

You are 33 years old.
You are 25 years old.

Parameters make functions flexible.

Without parameters, functions always do the same thing.

With parameters, functions can adapt.

Like a good tool.

Or a very polite waiter.

Multiple Parameters

A function can have more than one parameter.

Example:

function introduceUser(firstName, age) {
  console.log(`${firstName} is ${age} years old.`);
}

introduceUser("Viktor", 33);
introduceUser("Anna", 25);

Output:

Viktor is 33 years old.
Anna is 25 years old.

Order matters.

This:

introduceUser("Viktor", 33);

is not the same as this:

introduceUser(33, "Viktor");

JavaScript will not say:

“Hmm, maybe you meant the opposite.”

It will simply use the values in the order you gave them.

JavaScript is literal.

Very literal.

Like a robot reading a shopping list.

Return Values

Sometimes a function should not only do something.

Sometimes it should calculate something and give back a result.

For that, we use return.

Example:

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

const result = addNumbers(5, 3);

console.log(result);

Output:

8

What happened?

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

The function calculates a + b.

Then return sends the result back.

const result = addNumbers(5, 3);

The returned value is stored in result.

Important:

return gives a value back from the function.

console.log() only prints something.

They are not the same.

console.log vs return

This function prints a value:

function addNumbers(a, b) {
  console.log(a + b);
}

const result = addNumbers(5, 3);

console.log(result);

Output:

8
undefined

Why undefined?

Because the function printed 8, but did not return anything.

Now compare:

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

const result = addNumbers(5, 3);

console.log(result);

Output:

8

This time the function returned the value.

Simple rule:

Use console.log() to inspect.

Use return to give a value back.

The console is for your eyes.

Return is for your program.

Very different jobs.

Do not confuse the waiter with the kitchen.

Functions with Conditions

Functions can use if, else, and else if.

Example:

function checkAge(age) {
  if (age >= 18) {
    return "You can enter.";
  } else {
    return "You are too young.";
  }
}

console.log(checkAge(20));
console.log(checkAge(15));

Output:

You can enter.
You are too young.

This function receives an age.

Then it returns a message depending on the age.

This is powerful.

You can put logic inside functions and reuse it anywhere.

The function becomes a little decision machine.

Hopefully not too judgmental.

Function Expressions

There is another way to create functions.

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

greetUser();

This is called a function expression.

The function is stored in a variable.

For now, both styles are useful:

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

and:

const sayHello = function () {
  console.log("Hello!");
};

In this beginner course, we will mostly use the first style because it is easier to read.

Later, you will see function expressions often.

JavaScript has many ways to do the same thing.

Because apparently one way was too peaceful.

Arrow Functions

Modern JavaScript also has arrow functions.

Example:

const greetUser = () => {
  console.log("Hello!");
};

greetUser();

Another example with parameters:

const addNumbers = (a, b) => {
  return a + b;
};

console.log(addNumbers(5, 3));

Arrow functions are common in modern JavaScript.

You will see them in React, Next.js, and many other tools.

For now, understand the idea:

An arrow function is another way to write a function.

Do not panic if it looks strange.

It is just JavaScript wearing modern glasses.

Build a Price Calculator

Now let us build a small function that calculates a final price.

Replace script.js with this:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

const coursePrice = 49;
const courseDiscount = 10;

const finalPrice = calculateFinalPrice(coursePrice, courseDiscount);

console.log(`Final price: €${finalPrice}`);

Output:

Final price: €39

This is useful because the calculation is reusable.

You can calculate many prices:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

console.log(calculateFinalPrice(49, 10));
console.log(calculateFinalPrice(100, 25));
console.log(calculateFinalPrice(80, 15));

Output:

39
75
65

One function.

Many results.

That is the magic.

Not real magic.

Better.

Debuggable magic.

Functions and the DOM

Now let us use functions with HTML.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Functions</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    button {
      background-color: #2563eb;
      color: white;
      border: none;
      padding: 14px 20px;
      border-radius: 999px;
      font-weight: 700;
      cursor: pointer;
    }

    button:hover {
      background-color: #1d4ed8;
    }

    .success {
      color: #15803d;
      font-weight: 700;
    }

    .warning {
      color: #b45309;
      font-weight: 700;
    }

    h1 {
      font-size: 42px;
    }

    p {
      font-size: 20px;
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <h1>Functions</h1>

  <div class="card">
    <h2 id="productName">JavaScript Course</h2>
    <p id="productPrice">Price: €49</p>
    <p id="productStatus">Click the button to check the discount.</p>
    <button id="checkButton">Check Discount</button>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const productStatusElement = document.getElementById("productStatus");
const checkButton = document.getElementById("checkButton");

function calculateFinalPrice(price, discount) {
  return price - discount;
}

function showPriceMessage() {
  const price = 49;
  const discount = 10;
  const budget = 45;

  const finalPrice = calculateFinalPrice(price, discount);

  if (finalPrice <= budget) {
    productStatusElement.textContent = `Good news! Final price is €${finalPrice}. You can buy it.`;
    productStatusElement.className = "success";
  } else {
    productStatusElement.textContent = `Final price is €${finalPrice}. It is over your budget.`;
    productStatusElement.className = "warning";
  }
}

checkButton.addEventListener("click", showPriceMessage);

Refresh the browser.

Click the button.

JavaScript runs the function.

The function calculates the final price.

Then it shows a message on the page.

This is very close to real web development.

User action.

Function runs.

Data changes.

Page updates.

Beautiful.

The browser is no longer just sitting there like a decorative potato.

How This Code Works

This finds the paragraph:

const productStatusElement = document.getElementById("productStatus");

This finds the button:

const checkButton = document.getElementById("checkButton");

This function calculates the final price:

function calculateFinalPrice(price, discount) {
  return price - discount;
}

This function updates the page:

function showPriceMessage() {
  const price = 49;
  const discount = 10;
  const budget = 45;

  const finalPrice = calculateFinalPrice(price, discount);

  if (finalPrice <= budget) {
    productStatusElement.textContent = `Good news! Final price is €${finalPrice}. You can buy it.`;
    productStatusElement.className = "success";
  } else {
    productStatusElement.textContent = `Final price is €${finalPrice}. It is over your budget.`;
    productStatusElement.className = "warning";
  }
}

This connects the button click to the function:

checkButton.addEventListener("click", showPriceMessage);

Notice something important:

We write:

showPriceMessage

not:

showPriceMessage()

Why?

Because we want JavaScript to run the function later, when the button is clicked.

If you write showPriceMessage(), the function runs immediately.

This is a common beginner mistake.

JavaScript is very literal.

Again.

Common Mistakes

Forgetting to Call the Function

Wrong:

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

This defines the function but does not run it.

Correct:

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

sayHello();

Functions do not run by themselves.

They are not cats.

They do not randomly decide to do things.

Usually.

Confusing Parameters and Arguments

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

greet("Anna");

name is the parameter.

"Anna" is the argument.

Parameter is the placeholder.

Argument is the real value.

Simple.

Powerful.

Slightly fancy words.

Forgetting return

Wrong:

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

const result = add(2, 3);

console.log(result);

Output:

undefined

Correct:

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

If you want a function to give back a value, use return.

JavaScript will not guess.

JavaScript does not do emotional interpretation.

Calling a Function Too Early in an Event Listener

Wrong:

button.addEventListener("click", showMessage());

Correct:

button.addEventListener("click", showMessage);

Without parentheses, you pass the function.

With parentheses, you call it immediately.

This one is important.

Very important.

This bug loves beginners.

Do not feed it.

Practice

Create a function named createGreeting.

It should accept one parameter:

It should return:

Hello, NAME!

Example:

function createGreeting(name) {
  return `Hello, ${name}!`;
}

const message = createGreeting("Viktor");

console.log(message);

Then create another function named checkAccess.

It should accept:

Rules:

Example:

function checkAccess(age, hasTicket) {
  if (age >= 18 && hasTicket) {
    return "Access granted";
  }

  return "Access denied";
}

console.log(checkAccess(22, true));
console.log(checkAccess(16, true));
console.log(checkAccess(30, false));

Run it.

Change values.

Break it.

Fix it.

This is how functions become normal.

Mini Challenge

Build a small page with:

Create these functions:

function calculateFinalPrice(price, discount) {
  return price - discount;
}
function createPriceMessage(finalPrice) {
  return `The final price is €${finalPrice}.`;
}

When the user clicks the button:

Bonus:

Add a budget.

If final price is less than or equal to budget, show a success message.

Otherwise, show a warning message.

This is exactly how real websites work.

Small functions.

Clear responsibilities.

Clean logic.

Less spaghetti.

More lasagna.

Structured layers.

Very Italian-friendly code.

Summary

Today you learned:

This is a huge step.

Functions are everywhere in JavaScript.

Once you understand functions, the language becomes much easier to organize.

Without functions, code becomes a messy drawer.

With functions, code becomes a toolbox.

Still messy sometimes.

But at least the hammer has a place.

Next Lesson

In the next lesson, we will learn arrays.

Arrays help you store lists of values.

Names.

Products.

Tasks.

Scores.

Basically, when one variable is not enough, arrays arrive.

With brackets.

And opinions.