Unays Learn · JavaScript

JavaScript basics: variables, functions and events

JavaScript makes web pages interactive. In this tutorial you will learn the core ideas of programming and finish with a working click counter.

Variables

A variable is a named box that holds a value. Use const when the value will not be replaced and let when it will:

const name = "Arta";
let score = 0;
score = score + 10;
console.log(name, score); // Arta 10

Common value types are strings (text in quotes), numbers, booleans (true or false), arrays (lists) and objects (named properties):

const colors = ["red", "green", "blue"];
const student = { name: "Arta", grade: 8 };
console.log(colors[0]);     // red
console.log(student.grade); // 8

Decisions and loops

Use if to run code only when a condition is true:

const temperature = 31;
if (temperature > 30) {
  console.log("It is hot today.");
} else {
  console.log("It is not too hot.");
}

Use a loop to repeat work. for...of goes through each item of an array:

for (const color of colors) {
  console.log("I like " + color);
}

Use === to compare values. It checks both the value and the type, which avoids surprising results such as "5" == 5 being true.

Functions

A function is a reusable set of steps. It can take inputs (parameters) and give back a result with return:

function average(numbers) {
  let total = 0;
  for (const n of numbers) total += n;
  return total / numbers.length;
}

console.log(average([8, 9, 10])); // 9

Give functions names that say what they do, and keep each one focused on a single job.

Responding to clicks

JavaScript can find elements on the page and react to events such as clicks. Here is a complete click counter:

<button id="add">Add one</button>
<p>Clicks: <span id="count">0</span></p>

<script>
  const button = document.querySelector("#add");
  const output = document.querySelector("#count");
  let clicks = 0;

  button.addEventListener("click", () => {
    clicks += 1;
    output.textContent = clicks;
  });
</script>
  • document.querySelector finds the first element that matches a CSS selector.
  • addEventListener("click", ...) runs the function every time the button is clicked.
  • textContent changes the text inside an element safely.

Use the console

When something does not work, open the browser's developer tools (F12, or right-click and choose Inspect) and look at the Console. Errors appear there with a line number, and console.log() lets you print values to check what your code is doing. The debugging guide explains how to read these messages.

Try it yourself

In Unays Code, extend the counter: add a "Reset" button, and change the text colour to green when the count reaches 10.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].