← Web basics: HTML, CSS and JavaScript

Your first JavaScript: variables

Where scripts go, and how to store values with let and const.

Start this lesson

JavaScript is a programming language that runs inside the browser. You write it in a <script> element, usually just before </body>, so the HTML above it already exists when the script runs. The first building block is a variable: a named box that holds a value. Write const for a box whose value will never be replaced, and let for one whose value will change. Each instruction (statement) usually ends with a semicolon, and // starts a comment that the computer ignores.

<p id="out"></p>
<script>
  const city = "Accra";    // never changes
  let visitors = 10;       // will change
  visitors = visitors + 5; // now 15
  console.log(visitors);   // shows 15 in the developer console
  document.querySelector("#out").textContent = city + " has " + visitors + " visitors";
</script>

city is a const holding text; visitors is a let that we update. The last line puts a sentence into the paragraph with id out (you will learn that line properly soon). The page shows: Accra has 15 visitors.

console.log shows a value in the browser's developer console (open it with F12 or right-click → Inspect). It is how programmers peek inside a running program.

Variable names cannot contain spaces. The usual style is camelCase: firstName, totalPrice, isOpen.

Assigning to a const again gives an error like "Assignment to constant variable". If you meant to change it, use let.