Skills / JavaScript for the web / First steps: variables, values and the console

JavaScript for the web, lesson 1 of 8

First steps: variables, values and the console

JavaScript is the programming language of the web: every browser runs it. You can try it right now without installing anything. Open any page, press F12 (or right-click and choose Inspect), and click the Console tab. Type a line and press Enter, and the browser runs it.

A variable is a named box for a value. Create one with let if it may change, or const if it never will:

  • const siteName = "Bakery"; stores some text (a string, always in quotes)
  • let visitors = 120; stores a number
  • let isOpen = true; stores a boolean, which is either true or false

You can then use and change them: visitors = visitors + 1; adds one, and console.log(visitors) prints the value in the console, which is the simplest way to see what your code is doing.

Strings can be joined, and template strings make that tidy. Use backticks and ${...} to insert a value: ` Welcome to ${siteName} ` gives "Welcome to Bakery".

Three habits save beginners hours:

  • Use const by default and let only when the value really changes
  • Give variables names that say what they hold (totalPrice, not x)
  • End statements with a semicolon, and keep one statement per line

JavaScript is case-sensitive: total and Total are two different variables.

Try it: In your browser console, create a const called name holding your name and a let called age. Add 1 to age, then log a sentence like "Asha is 21" using a template string.

Check yourself

1. Which keyword should you use for a value that will never change?

2. What does console.log(x) do?

3. Are total and Total the same variable in JavaScript?