Skip to content

First steps in JavaScript

About 40 minutes · read, practise, then check your understanding

JavaScript makes pages respond: buttons that do something, forms that check input, content that changes. It is also the most widely used programming language for beginners entering web jobs.

You will learn

  • Where JavaScript runs and how to add it to a page
  • Variables with let and const
  • How to react to a button click
  • How to read an error in the console

Before you start

  • Lesson: Styling with CSS

The idea, simply

JavaScript is a programming language that runs inside the browser. Unlike HTML and CSS, it can make decisions, remember values and react to what the user does.

A variable is a named box that holds a value. Use const for values that will not change and let for values that will.

const name = "Meena";   // will not change
let count = 0;          // will change
count = count + 1;      // count is now 1
console.log(name, count);
console.log prints values in the browser's console, a developer's notebook

To make a button do something, you find it in the page and tell the browser what to run when it is clicked. The page itself is available to JavaScript as document.

<button id="hello">Say hello</button>
<p id="message"></p>

<script>
  const button = document.querySelector("#hello");
  const message = document.querySelector("#message");

  button.addEventListener("click", function () {
    message.textContent = "Vanakkam! You clicked the button.";
  });
</script>
querySelector finds an element; addEventListener says what to do on a click
  1. document.querySelector("#hello") finds the element with id="hello", using the same selectors as CSS.
  2. addEventListener("click", function () { ... }) means: when this is clicked, run the code inside the curly braces.
  3. textContent changes the text inside an element.

See it in action

<p>Water glasses today: <strong id="glasses">0</strong></p>
<button id="add">+1 glass</button>

<script>
  let glasses = 0;
  const display = document.querySelector("#glasses");

  document.querySelector("#add").addEventListener("click", function () {
    glasses = glasses + 1;
    display.textContent = glasses;
  });
</script>
A counter: let holds a changing value, and each click updates the page

Common mistakes

Putting the <script> before the elements it looks for.
Put scripts at the end of the body so the elements already exist.
Mixing up = and ===.
= stores a value; === compares two values.
Copying code without reading the console errors.
Read the first error: it names the problem and the line.

Key takeaways

  • JavaScript runs in the browser and can react to the user.
  • const for fixed values, let for changing ones.
  • querySelector finds elements; addEventListener reacts to clicks; textContent changes text.