Skip to main content
Back to module
JavaScript Essentials · Language Fundamentals

Variables and types

Reading37mLesson 1 of 4 in this module

Store values with let and const, and learn the handful of types every JavaScript value belongs to.

Why this matters

Every program remembers things: a score, a username, whether a menu is open, the items in a cart. In JavaScript you remember a value by giving it a name with a variable. Before you can write anything interactive you need to know how to create variables, when they can change, and what kind of value each one holds. Most beginner bugs in JavaScript come from a value being a different type than you thought, so this lesson is worth getting right.

Declaring variables: let and const

Modern JavaScript has two everyday keywords for variables:

const siteName = "Coding Help"; // cannot be reassigned
let score = 0;                   // can be reassigned

score = score + 10;  // fine: score is now 10
siteName = "Other";  // TypeError: Assignment to constant variable.
  • Use const by default. It tells the reader (and you, next week) that this name will always point to the same value.
  • Use let when the value genuinely needs to change, such as a counter or a running total.

You will also see var in older code and tutorials. It still works, but it has confusing rules: it ignores block boundaries ({ }) and can be used before the line that declares it. New code should use let and const.

A const stops you from reassigning the name, not from changing what is inside an object or array. const cart = []; cart.push("pen"); is allowed, because cart still points to the same array.

Naming rules

Names can contain letters, digits, _ and $, but cannot start with a digit. JavaScript is case-sensitive, so score and Score are different variables. The convention is camelCase: lessonCount, isLoggedIn, firstName. Pick names that say what the value means, not what type it is: price beats num1.

The types of values

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

typeexamplesnotes
number42, 3.14, -7one type for whole numbers and decimals
string"hello", 'hi', `Hi ${name}`text; backticks allow ${} placeholders
booleantrue, falseyes/no answers
undefinedundefineda variable that has no value yet
nullnull"deliberately empty"
object{ name: "Ada" }, [1, 2, 3]collections of values (arrays are objects)

You can ask JavaScript for a value's type with the typeof operator:

typeof 42          // "number"
typeof "42"        // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof { a: 1 }    // "object"
typeof [1, 2]      // "object"  (arrays are objects)
typeof null        // "object"  (a famous old bug, kept for compatibility)

The last two surprise everyone. To tell an array apart, use Array.isArray(value). To test for null, compare directly: value === null.

Template strings

Backtick strings let you drop values straight into text:

const name = "Ada";
const lessons = 13;
console.log(`${name} has ${lessons} lessons left.`);
// Ada has 13 lessons left.

This is much easier to read than name + " has " + lessons + " lessons left.".

Type coercion: when JavaScript guesses

JavaScript will quietly convert types when you mix them, and the results are not always what you expect:

"5" + 3     // "53"  (the + joins strings)
"5" - 3     // 2     (- only works on numbers, so "5" becomes 5)
"5" == 5    // true  (loose equality converts first)
"5" === 5   // false (strict equality compares type too)

Two habits avoid most of this:

  1. Always use === and !== for comparisons.
  2. Convert on purpose. Text from a form field is always a string, so turn it into a number before doing maths: Number("5") gives 5, and Number("abc") gives NaN ("not a number"). Check with Number.isNaN(value).

A worked example

Suppose a game stores a player's progress:

const playerName = "Sam";
let level = 1;
let lives = 3;
const hasShield = false;

level = level + 1;   // levelled up
lives = lives - 1;   // lost a life

console.log(`${playerName}: level ${level}, ${lives} lives`);
console.log(typeof level, typeof playerName, typeof hasShield);
// Sam: level 2, 2 lives
// number string boolean

playerName and hasShield never change, so they are const. level and lives change, so they are let.

Common mistakes

  • Reassigning a const. If you need to change it, it should be let.
  • Using a variable before declaring it. With let and const this throws a ReferenceError. Declare first, use after.
  • Doing maths on strings. "10" + "5" is "105". Convert input with Number() first.
  • Trusting typeof for null and arrays. Use === null and Array.isArray().
  • Using ==. Prefer === so no conversion happens behind your back.

Quick recap

  • const for values that do not get reassigned, let for ones that do; avoid var.
  • The everyday types are number, string, boolean, undefined, null and object (arrays are objects).
  • typeof tells you a type, with two quirks: null and arrays both say "object".
  • Use ===, and convert strings to numbers on purpose.

Try it

Open the Do tab. You will declare a constant and a counter, then write a small typeLabel function that fixes the two typeof quirks.

Also in this lesson: