Find a course

Module 1: Getting StartedLesson 2 of 1212 min

Variables and Data Types

Store values with let and const, learn numbers, strings, booleans, null and undefined, and check types with typeof, avoiding the classic beginner traps.

Step 1 of 14Learn

Giving values a name

Imagine an online store calculating your order. It needs to remember the price of each item, how many you want, and whether you have a coupon. Programs remember things in variables: named containers for values.

let quantity = 3;
const price = 19.99;
let total = price * quantity;
console.log(total); // 59.97
  • let creates a variable whose value can change later: quantity = 4; is allowed.
  • const creates a variable that cannot be reassigned. Writing price = 25; throws a TypeError.
  • var is the older way. It has confusing scoping rules, so modern code uses let and const instead. You will still see var in older tutorials.

A good default: use const unless you know the value must change, then use let. This makes code easier to read, because a reader knows a const will hold the same value everywhere.

Naming rules: names can contain letters, digits, _ and $, but cannot start with a digit or be a reserved word like let or if. By convention, JavaScript uses camelCase: totalPrice, isLoggedIn, userName. Choose names that say what the value means. t saves three seconds of typing and costs minutes of confusion later; totalWithTax explains itself.

Step 2 of 14Compare

let, const and var side by side

Aspectletconstvar
Can be reassigned?YesNo (TypeError)Yes
ScopeBlock { }Block { }Whole function
Typical useCounters, totals that changeDefault choice for most valuesOld code only
Use in new code?Yes, when the value changesYes, by defaultAvoid

Step 3 of 14Practice · What would you do?

What would you do?

You are writing code for a game. Which declaration is the best fit for the player's score, which goes up every time they collect a coin?

Step 4 of 14Learn

The basic data types

Every value in JavaScript has a type. The ones you will use constantly:

TypeExamplesNotes
number42, 3.14, -7One type for whole numbers and decimals
string"cat", 'hi'Text, in double quotes, single quotes or backticks
booleantrue, falseYes/no values for decisions
undefinedundefinedA variable declared but not given a value
nullnullDeliberately "no value," set by the programmer

There are also objects (including arrays and functions), which you will meet later, plus two rarer types, bigint and symbol.

The typeof operator tells you a value's type:

typeof 42        // "number"
typeof "42"      // "string"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object"  (a famous bug from 1995, kept for compatibility)

Notice that 42 and "42" are different types. One is a number you can do math with; the other is two characters of text. Mixing them up is the source of many beginner bugs, especially with values typed into web forms, which always arrive as strings.

Step 5 of 14Practice · Diagram

The family tree of JavaScript values

Which branch do arrays such as [1, 2, 3] belong to?

Tap the shape that answers the question, then press Check.

The family tree of JavaScript valuesHierarchy diagram: Every value, Primitives, Objects, number, string, boolean, undefined, null, bigint, symbol, plain objects { }, arrays [ ], functions.Every valuePrimitivesnumberstringbooleanundefinednullbigint, symbolObjectsplain objects { }arrays [ ]functions
Every value
Primitives

Simple, immutable values compared by their content.

Objects

Containers compared by reference: two separate objects are never ===.

number
string
boolean
undefined
null
bigint, symbol
plain objects { }
arrays [ ]
functions

Step 6 of 14Practice · Sort into groups

Sort each value by its type.

Tap an item, then tap its group (or drag it there).

Step 7 of 14Learn

Numbers and strings up close

Numbers support the usual arithmetic: +, -, *, /, and ** for powers (2 ** 10 is 1024). Two surprises are worth knowing early:

  • Decimals are approximate. 0.1 + 0.2 gives 0.30000000000000004, because computers store numbers in binary. For money, work in whole cents (1999 instead of 19.99) or round when displaying.
  • NaN means "Not a Number." It appears when math fails, such as "abc" * 2. Oddly, typeof NaN is "number".

Strings have a length and many built-in methods, functions attached to the value:

const name = "Ada Lovelace";
name.length          // 12
name.toUpperCase()   // "ADA LOVELACE"
name.includes("Love")// true
name[0]              // "A" (positions start at 0)

Template literals, written with backticks, let you insert values with ${...}:

const items = 3;
console.log(`You have ${items} items in your cart.`);

To turn a string into a number, use Number("42") (gives 42) or parseInt("42px") (gives 42, ignoring the trailing text). Number("42px") gives NaN.

Step 8 of 14Note

Step 9 of 14Flashcards

String tools you will use constantly

Tap a card to flip it.

Step 10 of 14Practice · Code challenge

Write a function describe(name, age) that returns a string in exactly this format: "Maya is 29 years old". Use a template literal.

Runs in a sandbox in your browser.
  • describe("Maya", 29)
  • describe("Leo", 7)

Step 11 of 14Note

Step 12 of 14Practice · Choose one

What is the value of typeof "7" + 3? (Hint: typeof runs before +.)

Step 13 of 14Note

Step 14 of 14Practice · Fill in the blanks

Fill in the blanks

After const city = "Paris";, the expression city.length gives , and city[1] gives the letter .