JavaScript Functions

Package code into reusable, named blocks with inputs and outputs.

Lesson 17 of 56Beginner13 min read

A function is a reusable recipe: a named block of code that you write once and run whenever you need it. You give it some ingredients (inputs), it does its job, and it hands back a result (output).

Functions are the most important building block in JavaScript. They stop you repeating the same code in several places, they give a clear name to each task, and they let you test one small piece at a time. Every real app is made of many small functions working together.

Declaring and calling a function

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

greet(); // call it
greet(); // and again

Writing a function, called declaring it, doesn't run it. Calling it, by writing its name followed by (), does. You can call the same function as many times as you like.

Forgetting the brackets is a common slip. greet on its own refers to the function without running it, so nothing happens.

Parameters and arguments

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

greet("Ada");   // Hello, Ada!
greet("Linus"); // Hello, Linus!
  • name is a parameter, a placeholder in the function's definition.
  • "Ada" is an argument, the real value you pass in when calling it.
  • Separate several parameters with commas: function add(a, b).
  • Missing arguments become undefined. Give a default value with =: function greet(name = "friend").

Parameters are what make a function reusable. The same function can greet anyone, add any two numbers or format any price.

return: sending a result back

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

const total = add(2, 3); // 5
  • return sends a value back to the place where the function was called.
  • It also ends the function immediately, so code after it doesn't run.
  • A function without return gives back undefined.

Printing with console.log and returning are different. Logging shows a value to you in the console; returning hands it to your code so you can store it, compare it or pass it to another function.

Function expressions

Functions are values, so you can store them in variables:

JavaScript
const square = function (n) {
  return n * n;
};

This works like a function declaration, with one difference: a declared function can be called before the line where it's written, but a function stored in a variable can't. The next lesson covers the shorter arrow functions.

JavaScript Functions Syntax

Function syntax

function name(param1, param2 = defaultValue) {
  // body
  return result;
}

const result = name(arg1, arg2);

JavaScript Functions Summary

  • A function is a named, reusable block of code.
  • Declaring a function defines it; calling it with () runs it.
  • Parameters are placeholders; arguments are the values passed in.
  • return sends a result back and ends the function.
  • Keep functions small, focused and clearly named.

JavaScript Functions Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Your first functions

function sayHi() {
  console.log("Hi there! 👋");
}

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

sayHi();
greet("Priya", "🎉");
greet("Tom");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 3A function with no parameters.
  2. Line 5Two parameters; the second has a default value.
  3. Line 9Calling runs the body.
  4. Lines 10 to 11Different arguments, different output. Tom gets the default emoji.
Example 2

Returning values

function celsiusToFahrenheit(c) {
  return c * 9 / 5 + 32;
}

function isFreezing(c) {
  return c <= 0;
}

const today = 18;
const f = celsiusToFahrenheit(today);

console.log(`${today}°C is ${f}°F`);
console.log("Freezing?", isFreezing(today));
console.log("Boiling point:", celsiusToFahrenheit(100));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 2return hands the result back.
  2. Line 6Functions that answer yes/no questions often start with is/has.
  3. Line 10Store a function's result in a variable.
  4. Line 14Or use it directly inside another expression.
Example 3

Early return and reuse

function shippingCost(total) {
  if (total >= 50) {
    return 0;
  }
  return 4.99;
}

function checkoutTotal(items) {
  let sum = 0;
  for (const price of items) sum += price;
  return sum + shippingCost(sum);
}

console.log(checkoutTotal([20, 15]));
console.log(checkoutTotal([30, 25]));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 2 to 4Return early. Once return 0 runs, the function ends.
  2. Lines 8 to 12One function calls another. Small pieces combine into bigger ones.
  3. Lines 14 to 1535 + 4.99, and 55 + 0 (no delivery charge).

Common JavaScript Functions Mistakes

Forgetting the brackets

Don't
function roll() { return Math.ceil(Math.random() * 6); }
console.log(roll); // prints the function itself
Do
console.log(roll()); // calls it and prints the result

Logging instead of returning

Don't
function double(n) {
  console.log(n * 2);
}
const result = double(4) + 1; // NaN, because double returned undefined
Do
function double(n) {
  return n * 2;
}
const result = double(4) + 1; // 9

Code after return

Don't
function getPrice() {
  return 10;
  console.log("Never runs");
}
Do
function getPrice() {
  console.log("Getting price");
  return 10;
}

JavaScript Functions in Real Projects

Functions everywhere

formatDate(date), addToCart(product), validateEmail(text) and calculateTax(amount) are typical: real codebases are made of thousands of small, well-named functions. Libraries you'll use later, such as React, are largely a way of organising functions.

JavaScript Functions Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the function so it returns the area of a rectangle.

 area(width, height) {
   width * height;
}
console.log(area(3, 4)); // 12
Predict the outputeasy

What does this print?

function add(a, b = 10) {
  return a + b;
}
console.log(add(5), add(5, 1));
Predict the outputmedium

What does this print?

function shout(word) {
  console.log(word.toUpperCase());
}
const result = shout("hey");
console.log(result);
Fix the bugmedium

getInitials("Grace Hopper") should return "GH". Fix the function.

function getInitials(fullName) {
  const parts = fullName.split(" ");
  const initials = parts[0][0] + parts[1][0];
  console.log(initials);
}

console.log(getInitials("Grace Hopper"));
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • getInitials returns "GH"
  • Works for another name

JavaScript Functions Quiz

4 questions to check what you learned.

  1. How do you call a function named start?

    • call start
    • start
    • start()
    • function start()
  2. What's the difference between a parameter and an argument?

    • There is no difference
    • Arguments are in the definition
    • Parameters are always numbers
    • Parameters are placeholders in the definition; arguments are the actual values passed in
  3. What does a function return if it has no return statement?

    • undefined
    • null
    • 0
    • An error
  4. What happens to code written after return in the same block?

    • It runs after the return
    • It never runs
    • It runs before the return
    • It causes a syntax error

JavaScript Functions Challenge

Write a price formatter

Write a function formatPrice(amount, currency = "£") that:

  1. Returns the currency symbol followed by the amount with 2 decimals
  2. formatPrice(5) → "£5.00"
  3. formatPrice(12.5, "$") → "$12.50"

Then log both results.

ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • formatPrice(5) is "£5.00"
  • formatPrice(12.5, "$") is "$12.50"
  • formatPrice(0.1, "€") is "€0.10"
  • It returns (not just logs)