JavaScript is the language that makes web pages move and respond to clicks. HTML sets the page content, CSS sets the look, JavaScript sets the behavior. This tutorial covers the basics: variables, data types, functions, branching, loops, and the DOM.

Running JavaScript

The fastest way: open the browser console. Press F12 in Chrome or Firefox, then pick the Console tab. Type code there, press Enter, and the result shows at once.

For your own file, save the code in a separate .js file. Load that file in the HTML right before the closing </body> tag. If it loads in the <head>, use the defer attribute so the page loads first. Without that, JavaScript can run before the page elements exist, then fail.

Variables: let and const

A variable is a labeled box that stores a value. Write the name once, then reuse its value many times.

Use let for values that can change. Use const for values that stay fixed.

let age = 25;
const name = "Briyan";

age = 26; // fine, because let
name = "Febri"; // error, because const cannot change

Variable names are case-sensitive. name and Name are two different variables. One wrong letter, and the code fails because the variable is not found.

Variables are like labeled boxes

Basic data types

There are three data types you will use most. A string is text, written between quotes. A number is a number, written without quotes. A boolean holds only true or false.

let name = "Briyan"; // string
let age = 25; // number
let hasEaten = true; // boolean

Check a data type with typeof. For example, typeof name gives “string”.

console.log(typeof name); // "string"
console.log(typeof age); // "number"

Functions

A function is a named block of code you can call again and again. Write it once, use it anywhere. A function can take input (parameters) and give back a result (return).

function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Briyan")); // "Hello, Briyan!"
console.log(greet("Kirana")); // "Hello, Kirana!"

Call a function by writing its name, then parentheses. Put the values to send inside the parentheses. Forget the parentheses, and the function never runs — only its name is mentioned.

if / else

if runs code only when its condition is true. else runs other code when the condition is false. This is called branching.

let age = 20;

if (age >= 18) {
  console.log("You may enter");
} else {
  console.log("Not yet");
}

Common comparison operators: === (equal to), !== (not equal to), > (greater than), < (less than), >= and <=.

Warning: to compare, use === (three equals signs). A single equals sign (=) means assigning a value, not comparing. Use the wrong one, and the condition is always true.

if / else flow (branching)

for loops

A loop repeats code without writing it many times. Use for when you know how many times to repeat.

for (let i = 1; i <= 5; i++) {
  console.log("Count " + i);
}

The part let i = 1 is the starting value. The part i <= 5 is the stop condition. The part i++ adds one to i each round.

Warning: make sure the stop condition can be reached. If not, the loop runs forever (an infinite loop) and the browser tab freezes.

Basic DOM

The DOM (Document Object Model) is the page structure JavaScript can change. Every HTML element can be found by its id, then its text replaced.

Find an element with document.getElementById(“judul”). Replace its text with textContent.

const title = document.getElementById("judul");
title.textContent = "Hello, Briyan!";

Write this code after the element exists on the page. That is why scripts load at the end of <body>. If the id is mistyped, the result is null and the next line fails.

JavaScript changing page text

Seeing results in the console

Show any value with console.log(). This is the fastest way to check whether your code runs as expected.

let total = 2 + 3;
console.log(total); // 5
console.log("Name:", name);

Open the console with F12, then pick the Console tab. If there is an error, its message shows there, with the line number. Read the message first before guessing.

Common mistakes

  • Forgetting the closing curly brace { } on a function, if, or loop.
  • Mistyping a variable name, because upper and lower case differ.
  • Forgetting the closing quote on a string.
  • Comparing with =, when it should be ===.
  • Loading the script before the page elements exist, so getElementById returns null.
  • Forgetting the parentheses when calling a function.

If you get stuck, ask Muse (yue) to explain the line that fails. Paste the error message from the console so the answer is exact.

Full example program: click counter and greeting

Put it all together in one small program. This page has a “Klik saya” button (“Click me” in Indonesian) and a name field. Each button press adds one to the click count. If the name field is filled, it shows a greeting “Halo, name!” (“Halo” means “Hello”).

Copy the code below into a file called klik.html, then open that file in your browser. No server needed, nothing to install.

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Penghitung Klik</title>
</head>
<body>
  <h1 id="judul">Klik tombol di bawah</h1>
  <input id="nama" type="text" placeholder="Tulis namamu">
  <button id="tombol">Klik saya</button>
  <p id="hasil">Belum ada klik.</p>

  <script>
    let jumlahKlik = 0;
    const tombol = document.getElementById("tombol");
    const hasil = document.getElementById("hasil");
    const kolomNama = document.getElementById("nama");
    const judul = document.getElementById("judul");

    tombol.addEventListener("click", function () {
      jumlahKlik = jumlahKlik + 1;
      const nama = kolomNama.value;
      if (nama === "") {
        hasil.textContent = "Kamu sudah klik " + jumlahKlik + " kali.";
      } else {
        hasil.textContent = "Halo, " + nama + "! Kamu sudah klik " + jumlahKlik + " kali.";
      }
      judul.textContent = "Terima kasih sudah klik!";
    });
  </script>
</body>
</html>

How it works: addEventListener(“click”, …) means “when the button is clicked, run this function”. The variable jumlahKlik sits outside the function so its value survives each click. kolomNama.value reads the name field. If it is empty, show only the count. If it is filled, show the greeting plus the count.