JavaScript for Kids: First Steps with Code That Makes Pages Come Alive

ยท 2 min read ยท By the Tiny Coderz team

HTML builds a page and CSS styles it. JavaScript makes it do things: respond to clicks, change text, play a game. It runs in every web browser, so there is nothing to install.

Try it in two lines

Put this in the <body> of an HTML page:

<button onclick="alert('Hello!')">Click me</button>

Clicking the button shows a message box. onclick says what to do when clicked, and alert(...) shows a pop-up.

Variables

Variables work much as they do in other languages:

let score = 0;
score = score + 1;

let creates a variable. Each statement ends with a semicolon. (If your child already knows what a variable is from Scratch or Python, this will feel familiar.)

A click counter

<h1>Clicks: <span id="count">0</span></h1>
<button onclick="addOne()">Add one</button>

<script>
  let clicks = 0;

  function addOne() {
    clicks = clicks + 1;
    document.getElementById("count").textContent = clicks;
  }
</script>

What happens here:

  • <span id="count"> gives the number a name so JavaScript can find it.
  • function addOne() { ... } is a named chunk of code.
  • document.getElementById("count") finds that element, and .textContent changes what it shows.
  • Each click runs addOne, which increases clicks and updates the page.

Making decisions

if (clicks >= 10) {
  alert("Ten clicks - you win!");
}

Notice the curly braces { } and the round brackets around the condition. JavaScript uses === to check if two things are the same:

if (name === "Sam") { ... }

Loops

for (let i = 0; i < 3; i++) {
  console.log("Round " + i);
}

console.log writes to the browser's developer console (press F12 and look for the Console tab). It's the place to look when something doesn't work.

How it differs from Python

  • JavaScript uses { } and ;; Python uses indentation.
  • JavaScript works directly with the page, so you can change colours, text and pictures.
  • JavaScript's let creates variables; Python needs no keyword.

Common mistakes

  • Missing a closing bracket or brace.
  • Spelling getElementById wrong. It needs a capital E and a capital B and I and D, exactly.
  • Forgetting to put the <script> at the end of the page, so the elements don't exist yet.

Project ideas

  1. A button that changes the page's background colour.
  2. A "magic 8-ball" that picks a random answer.
  3. A tiny quiz that keeps score.

To keep going, read how the web works and try the free JavaScript course.

Try JavaScript Basics with your child

Every lesson in JavaScript Basics opens with an animated explanation, then a short practice. You can read a full sample lesson with no account.

Keep reading