Chapter 14

JavaScript Functions and Events

Write reusable functions and respond to user actions with event listeners.

JavaScript Functions and Events

A function is a reusable block of code that you can run whenever you need it. Events let your code react to what the user does, such as clicking a button. Together they are how pages become interactive.

Declaring and calling functions

Declare a function with the function keyword, a name, a list of parameters in brackets and a body in curly braces. You run it by writing its name followed by brackets, which is called calling the function.

function greet(name) {
  console.log('Hello ' + name);
}

greet('Aisha');   // runs the function
greet('Ben');

Parameters are the names in the declaration; the values you pass when calling are the arguments.

Returning a value

The return keyword sends a value back to whoever called the function. Once return runs, the function stops.

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

let total = add(3, 4);   // total is 7

A function without a return still runs its code but gives back undefined.

Arrow functions

ES6 added a shorter syntax called arrow functions, common for small helpers.

const square = (n) => {
  return n * n;
};
console.log(square(5));   // 25

Events

An event is something that happens on the page: a click, a key press, the page finishing loading. You respond by attaching a handler with addEventListener, which takes the event name and a function to run.

const button = document.querySelector('#save');

button.addEventListener('click', function () {
  console.log('Button was clicked');
});

The function you give is not called by you; the browser calls it when the event happens. This is why it is called a callback. Common event names include click, submit, keydown and mouseover.

Why functions matter

Functions let you write code once and reuse it, keep programs organised, and give names to steps so the logic reads clearly. Passing a function to an event listener is the everyday pattern that makes buttons and forms respond.

Remember: Calling a function needs the brackets, so use greet() not greet. With addEventListener you pass the function itself, without calling it, so the browser can run it later.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor