Functions & Events
1 min read2 lessons in topic
Learning objective
By the end of this lesson you will be able to write JavaScript functions and respond to a button click.
Functions let you package a piece of behaviour and reuse it. Events let your page react to what the user does.
Defining a function
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Kofi")); // Hello, Kofi!function declares a function; return sends a value back to the caller.
Responding to clicks
<button id="btn">Click me</button>
<script>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
document.body.style.backgroundColor = "#d9e1f4";
});
</script>addEventListener listens for an event — here a click — and runs the given function when it happens.
- Common events: click, submit, keydown, mouseover
- getElementById finds an element by its id
- Arrow functions (() => …) are a short way to write functions
Code playground
Run and edit the starter code — experiment freely.
javascript · runnable
Output appears here when you press Run.
Practice exercise
Write a function that converts Celsius to Fahrenheit and wire a button to run it.
Check your understanding
1. Which method listens for a button click?
2. What does return do inside a function?
Self-graded — answer then check below.