Learn/JavaScript/2. Values and variables
Lesson 2 of 15
Sign in

JavaScript, lesson 2

Values and variables

A variable is a name that points at a value. Once a value has a name, you can use it again, combine it with other values and change it later.

const and let

Modern JavaScript gives you two keywords for declaring variables:

Reach for const first. It tells readers (and you) that the value will not be replaced, and JavaScript throws a TypeError if you try. Switch to let only when you really reassign the variable, as with a counter or a running total. You may see an older keyword, var, in old code; it has confusing scoping rules, so avoid it.

Naming

Names may contain letters, digits, _ and , but cannot start with a digit. They are case sensitive: and are different variables. JavaScript style is : , , . Some teams write fixed configuration values in , such as .

2 exercises to try what you just read.

Exercise 1

Movie ticket

Press Ctrl Enter or Check to test your code.

Exercise 2

Game score

Press Ctrl Enter or Check to test your code.

$
total
Total
camelCase
firstName
itemCount
isReady
UPPER_SNAKE_CASE
const MAX_PLAYERS = 4;

The basic types

Every value has a type. The ones you will use all the time are:

TypeExamplesNotes
number42, -3.5, 1e6Whole numbers and decimals share one type.
string"hi", 'ok', `x`Text.
booleantrue, falseYes or no.
undefinedundefinedA variable that has no value yet.
nullnull"Deliberately empty".
bigint10nWhole numbers of any size.

The typeof operator tells you the type of a value as a string:

One historical quirk: typeof null gives "object", not "null". It is a bug from the very first version of the language that can never be fixed without breaking old websites.

JavaScript numbers are 64-bit floating point values. They are exact for whole numbers up to about nine quadrillion, but decimals can round slightly: 0.1 + 0.2 is 0.30000000000000004. For money you usually round when printing, which you will see soon.

Template literals

Strings written with backticks are template literals. Inside them, ${ } drops in the value of any expression. This is usually clearer than gluing strings with +:

Template literals may also span several lines; the line breaks become part of the string.

Constants are not frozen

const stops a name from being reassigned. It does not freeze the value itself. You will see this matter later with arrays and objects, whose contents can still change.

Further reading

  • MDN: Grammar and types
  • MDN: const
  • MDN: typeof
  • MDN: Template literals

Store these facts in const variables: the movie title Night Train, the seat F7, and the ticket price 9.5. Then use template literals to print exactly:

Compute the two-ticket price from the price variable instead of typing 19. The program reads no input.

A player starts a game with a score of 0. Use let for the score and update it step by step:

  1. They collect a coin: add 10.
  2. They find a treasure: add 50.
  3. They hit a trap: lose 15.
  4. A power-up doubles the score.

After each step print the step name and the new score, then print the type of the score with typeof. Expected output:

const city = "Lisbon";   // const: this name will always point at this value
let score = 0;           // let: you plan to reassign it later

score = score + 10;
console.log(city, score); // Lisbon 10
console.log(typeof 3.14);       // number
console.log(typeof "3.14");     // string
console.log(typeof false);      // boolean
let nothingYet;
console.log(typeof nothingYet); // undefined
const name = "Ada";
const age = 36;
console.log(`${name} is ${age} years old.`);     // Ada is 36 years old.
console.log(`Next year: ${age + 1}`);            // Next year: 37
Movie: Night Train
Seat: F7
Price: 9.5 EUR
Two tickets: 19 EUR
coin 10
treasure 60
trap 45
power-up 90
number