Skip to content
EzzyWeb

Level 2, Styling & Logic, Chapter 6 of 24

JavaScript Basics — Variables, Types & Operators

Why this matters

HTML gives a page structure and CSS gives it style, but neither can make a page react to what someone does, calculate a total, or remember information. That's where JavaScript comes in. It's the language that lets a page respond: validating a form before it submits, updating a total price as items are added to a cart, or showing a message when a button is clicked.

Every JavaScript program, no matter how advanced, is built from a small set of core ideas: storing information in variables, understanding what kind of information you're storing, and combining values with operators to produce new results. This chapter focuses on those foundations, and goes further than the surface level by looking at how values convert between types, how arrays store lists of information, and how to reach into the page itself with the DOM. Every effect you've seen on a JavaScript-powered website is built from exactly these building blocks.

The lesson

Storing information with variables

A variable is a named container for a value. In modern JavaScript, you create variables with let or const. Use const when the value should never be reassigned after it's set, and let when you expect the value to change later. Reaching for const first is a good habit, since it prevents accidental changes and makes your code easier to reason about. A variable name should describe what it holds, like userName or totalPrice, rather than a vague name like x, because clear names make code far easier to read later, including for you.

Declaring variables
JavaScript
1const siteName = "Trailhead Coffee";2let cupsSold = 0;34cupsSold = cupsSold + 1;5console.log(siteName, cupsSold);
const values cannot be reassigned; let values can. console.log prints values so you can check them.

Every value in JavaScript has a type. The most common types you'll use constantly are strings for text, wrapped in quotes like "hello", numbers for numeric values like 42 or 3.14, and booleans, which are either true or false and represent yes-or-no facts. There's also a special value, undefined, meaning a variable exists but hasn't been given a value yet. Knowing a value's type matters because operations behave differently depending on type: adding two numbers produces a sum, but adding two strings joins them together, a process called concatenation. JavaScript will also sometimes convert one type to another automatically, called type coercion; combining a string and a number with + always converts the number to a string first, which is convenient for building messages but can also cause bugs if you expect a number and get text instead.

  • String — text, written in quotes, like "Hello, world!"
  • Number — numeric values, like 7 or 19.99, no quotes needed
  • Boolean — true or false, used for yes-or-no logic
  • undefined — a variable that has been declared but has no value yet
  • Array — an ordered list of values, written with square brackets
Types and coercion in action
JavaScript
1const price = 4.5;2const quantity = 3;3const total = price * quantity;45const greeting = "Order total: $" + total;6console.log(greeting);78console.log(typeof price);9console.log(typeof greeting);
typeof reports a value's type as a string, which is handy for checking your assumptions while debugging.

Operators for math and comparison

Arithmetic operators work as you'd expect: + for addition, - for subtraction, * for multiplication, and / for division. The modulo operator, %, returns the remainder of a division, which is useful for checking things like whether a number is even. Comparison operators produce a boolean result. === checks whether two values are strictly equal, and !== checks whether they are not equal. Always prefer === over the older == operator, because === avoids surprising automatic type conversions. Comparison operators like >, <, >=, and <= compare numbers directly and also return booleans, which become essential in the next chapter when you use them to make decisions.

Comparisons return booleans
JavaScript
1const stock = 5;2const isSoldOut = stock === 0;3const isLowStock = stock <= 5 && stock > 0;4const isEven = stock % 2 === 0;56console.log(isSoldOut, isLowStock, isEven);
The && operator combines two boolean checks, only true when both sides are true.

Arrays store ordered lists of values, written with square brackets, like ["HTML", "CSS", "JavaScript"]. You can read an item by its position, called its index, starting at 0, so skills[0] is the first item. The .length property tells you how many items are in an array, and .push() adds a new item to the end. Arrays and the types above are the raw materials for almost every JavaScript program you'll write, including the loops and conditionals in the next chapter.

Working with an array
JavaScript
1const skills = ["HTML", "CSS", "JavaScript"];23console.log(skills[0]);4console.log(skills.length);56skills.push("Flexbox");7console.log(skills);
Index 0 is the first item; push adds a new item to the end of the array.

Connecting JavaScript to the page

You can also connect JavaScript to the HTML you already know how to write. The document.querySelector function finds an element on the page using a CSS selector, the very same selectors you learned in the CSS chapters, whether that's a tag name, a class starting with a dot, or an id starting with a hash. Once you have a reference to an element, you can read or change its content using properties like textContent, and you can add or remove CSS classes on it using classList.add() and classList.remove(), which is the standard way to toggle a visual state, like showing an element as active or highlighted. This is the bridge between the static pages you've built so far and pages that can update themselves.

Reading and changing an element
JavaScript
1const heading = document.querySelector("h1");2console.log(heading.textContent);34heading.textContent = "Welcome back!";5heading.classList.add("highlighted");
querySelector uses the same selector syntax from the CSS chapter to locate an element in the page.

Try it yourself

Practice declaring variables and using operators. Calculate a total price, then update the heading's text using document.querySelector, and add a CSS class to it.

Live preview

Chapter boss project

Boss Project: Build an Order Total Calculator

Write a small script that stores the price of an item and the quantity being purchased in variables, calculates the total cost, and displays the result by updating text on the page using document.querySelector.

Add at least one boolean check, such as whether the order qualifies for free shipping when the total is above a certain amount, and log that boolean to the console. Use classList.add to visually mark the message when free shipping applies.

Keep your variable names clear and descriptive, use const wherever a value doesn't need to change, and use typeof at least once while testing to confirm a value is the type you expect.

  • Start with two variables for price and quantity, then multiply them to get the total.
  • Use document.querySelector with a selector that matches an element already in your HTML.
  • Remember that combining a string and a number with + converts the number into text automatically.
  • For the free shipping check, use a comparison operator like >= to produce a boolean.
  • Try classList.add("some-class") on your result element and define that class in your CSS.

Level-up checklist

Tick these off once each one is true for you.