JavaScript: making your pages interactiveCreate account
Lesson 2 of 9

Variables and types

Programs need to remember things. A score in a game, the name someone typed, the number of items in a cart. In JavaScript you remember things with variables.

Variables are labeled boxes

A variable is like a box with a label on it. You put a value inside and use the label to get it back later.

javascript
let name = 'Alex';
console.log(name);

let creates the variable, name is the label and 'Alex' is the value inside. When you use name later, JavaScript looks inside the box and finds 'Alex'.

The single equals sign means "put this value in the box". It's not the same as equals in math, which trips up a lot of beginners. Read let name = 'Alex' as "let name hold Alex".

let and const

There are two ways to create a variable, and the difference matters:

javascript
let score = 0;
score = 10;       // fine, let can change

const birthYear = 1995;
birthYear = 2000; // error! const can't be reassigned
  • let creates a variable you can change later
  • const creates a variable that can't be reassigned

Here's a simple rule many developers follow: use const by default, and switch to let only when you know the value needs to change. It makes your code easier to understand, because when you see const, you know that value will stay the same.

You might also see var in older code. It's the old way of creating variables and has some confusing behavior. Stick with let and const.

Quick check

You're storing the number of tasks in a to-do list, which goes up and down. What should you use?

Select one answer

Naming variables

Good names make code readable. A few rules and habits:

  • Names can contain letters, numbers, _ and $, but can't start with a number
  • JavaScript uses camelCase for names with several words: the first word is lowercase and each new word starts with a capital letter, like firstName or totalPrice
  • Names are case sensitive, so score and Score are two different variables
  • Pick names that say what's inside. userAge is much clearer than x

Strings: text

Text is called a string, and it goes in quotes:

javascript
const greeting = 'Hello';
const city = "Stockholm";

You can join strings together with +:

javascript
const message = 'Hello, ' + name + '!';

But there's a nicer way, called template literals. Use backticks instead of quotes, and put variables inside ${ }:

javascript
const message = `Hello, ${name}! You live in ${city}.`;

Template literals are easier to read, especially with several variables, so you'll see them a lot. The backtick key is usually just below Escape, the same one you use to open the terminal in VS Code.

Strings also have useful built-in abilities, like:

javascript
'hello'.toUpperCase();    // 'HELLO'
'  hi  '.trim();          // 'hi'
'JavaScript'.length;      // 10

Numbers

Numbers don't need quotes, and you can do math with them:

javascript
const price = 120;
const quantity = 3;
const total = price * quantity;   // 360

The math operators are +, -, * (multiply) and / (divide).

Be careful with quotes. '5' with quotes is a string, not a number. And adding a string and a number gives you a string:

javascript
'5' + 3   // '53', not 8!

That one surprises everyone. If you have a number stored as a string, like something typed into a form, turn it into a real number first with Number('5').

Quick check

What is the result of '10' + 5 in JavaScript?

Select one answer

Booleans: true or false

A boolean can only be true or false. It's how programs answer yes or no questions:

javascript
const isLoggedIn = true;
const hasFinishedCourse = false;

Booleans become really useful in the next lesson, when your code starts making decisions.

Checking the type

If you're ever unsure what kind of value something is, use typeof:

javascript
typeof 'hello'   // 'string'
typeof 42        // 'number'
typeof true      // 'boolean'

There are a couple more types, like undefined for a variable that hasn't been given a value yet, but strings, numbers and booleans are the ones you'll use most.

Quick check

Which line creates a variable that can't be reassigned?

Select one answer

Try it yourself

In your script.js, create some variables about yourself:

  1. A const with your name
  2. A const with the year you were born
  3. A const that calculates your age from the current year with subtraction
  4. A let called coursesFinished that starts at 4 (you've finished four courses in this pathway!)
  5. Use a template literal and console.log to print a sentence using all of them, like "I'm Alex, I'm 30 and I've finished 4 courses"

Then try changing a const and read the error message in the console.