Skip to content
elephantoo

Variables & types

Lesson 2 of 34 14 min read

let, const and var, the primitive types, typeof, and === vs ==.


Programs work with data: names, prices, scores, lists of lessons. A variable is a named box that holds a value so you can use it later. Every value has a type that decides what you can do with it.

Declaring variables: const, let and var#

JavaScript
const siteName = "Elephantoo"; // cannot be reassigned
let lessonsDone = 0;           // can be reassigned
lessonsDone = lessonsDone + 1;

console.log(siteName, lessonsDone);
// siteName = "Other";  // TypeError: Assignment to constant variable.
Output
Elephantoo 1

Rule of thumb: use const by default; switch to let only when you truly need to reassign. Code full of const is easier to read because you know those values never change.

Why not var?

var is the original (pre-2015) keyword. It still works, but it has two surprising behaviours:

JavaScript
if (true) {
  var leaky = "I escape the block!";
  let contained = "I stay inside";
}
console.log(leaky);           // "I escape the block!"
console.log(typeof contained); // "undefined" – it doesn't exist out here
  1. var is function-scoped, not block-scoped, so it leaks out of if blocks and loops.
  2. var declarations are hoisted and initialised to undefined, so using one before its line gives undefined instead of an error.

let and const are block-scoped — they live only inside the nearest { }. You'll dig into this in the Scope, hoisting & closures lesson. In new code, never use var.

Naming rules

  • Names may contain letters, digits, _ and $, but can't start with a digit.
  • They're case-sensitive: score and Score are different.
  • Reserved words (let, class, return…) can't be used.
  • Convention: camelCase for variables and functions (totalPrice), PascalCase for classes (ShoppingCart), and UPPER_SNAKE_CASE for true constants (MAX_RETRIES).

const means "no reassignment", not "frozen"#

JavaScript
const scores = [10, 20];
scores.push(30);        // ✅ mutating the array is allowed
console.log(scores);    // [ 10, 20, 30 ]

const user = { name: "Ada" };
user.name = "Grace";    // ✅ changing a property is allowed
// user = {};           // ❌ TypeError: reassigning is not

The primitive types#

JavaScript has seven primitive types — simple, immutable values:

TypeExamplesNotes
string"hello", 'hi', `Hi ${name}`Text
number42, 3.14, -7, NaN, InfinityOne type for integers and decimals
bigint9007199254740993nWhole numbers of any size
booleantrue, falseYes/no
undefinedundefined"No value has been assigned"
nullnull"Intentionally empty"
symbolSymbol("id")Unique identifiers (advanced)

Everything else — arrays, functions, dates, plain {} objects — is an object. JavaScript is dynamically typed: a variable can hold any type, and the type belongs to the value, not the variable.

JavaScript
let value = 42;
value = "now a string"; // allowed (but confusing — avoid it)

Checking types with typeof#

JavaScript
console.log(typeof "hi");          // "string"
console.log(typeof 42);            // "number"
console.log(typeof 10n);           // "bigint"
console.log(typeof true);          // "boolean"
console.log(typeof undefined);     // "undefined"
console.log(typeof Symbol("x"));   // "symbol"
console.log(typeof {});            // "object"
console.log(typeof []);            // "object"  → use Array.isArray([])
console.log(typeof null);          // "object"  ← historical quirk!
console.log(typeof function () {}); // "function"

Because of these quirks, use Array.isArray(x) for arrays and x === null for null.

undefined vs null#

JavaScript
let notSetYet;
console.log(notSetYet); // undefined – JavaScript's default "nothing"

let selectedCourse = null; // you deliberately say "no course selected"

A good habit: let JavaScript produce undefined, and use null when you want to express "empty".

Numbers: a few gotchas#

JavaScript
console.log(0.1 + 0.2);            // 0.30000000000000004
console.log(7 / 2);                // 3.5  (no integer division)
console.log(Math.trunc(7 / 2));    // 3
console.log(Number("42"));         // 42
console.log(Number("42px"));       // NaN ("Not a Number")
console.log(parseInt("42px", 10)); // 42
console.log(Number.isNaN(NaN));    // true
console.log(2 ** 53 + 1);          // 9007199254740992 – precision lost!
console.log(2n ** 53n + 1n);       // 9007199254740993n

All numbers are 64-bit floating point, which is why 0.1 + 0.2 isn't exactly 0.3. For money, store whole units (paise, cents) as integers and format at the end. Integers are only exact up to Number.MAX_SAFE_INTEGER (2⁵³ − 1); beyond that, use bigint.

Template literals (a first look)#

Backticks let you embed expressions with ${} and span multiple lines:

JavaScript
const name = "Ada";
const lessons = 3;
console.log(`${name} has finished ${lessons} lessons.`);
console.log(`Next: lesson ${lessons + 1}`);
Output
Ada has finished 3 lessons.
Next: lesson 4

There's a whole lesson on strings coming up.

=== vs ==#

== (loose equality) converts types before comparing, which produces surprising results. === (strict equality) compares type and value:

JavaScript
console.log(0 == "");           // true   😬
console.log("1" == 1);          // true
console.log(null == undefined); // true

console.log(0 === "");          // false
console.log("1" === 1);         // false
console.log(NaN === NaN);       // false – NaN never equals anything

Always use === and !==. The next lesson explains exactly what == does and the one place some developers still use it.

Truthy and falsy#

In conditions, these eight values count as false (falsy): false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy — including "0", "false", [] and {}.

JavaScript
const input = "";
console.log(input || "Anonymous"); // "Anonymous"
const count = 0;
console.log(count || 10);          // 10 – oops, 0 was a valid value!
console.log(count ?? 10);          // 0  – ?? only replaces null/undefined

Common mistakes#

  • Using let for everything "just in case" — prefer const.
  • Comparing with == and being surprised.
  • Checking typeof x === "array" — that never works; use Array.isArray(x).
  • Doing money math with decimals like 19.99 * 3.

What's next#

You can store values and know their types. Next: operators — doing maths, comparing and combining values — and how JavaScript coerces types.

Check your understanding

Quick quiz

0/3 answered
  1. 1.Which declaration should you use by default for values that won't be reassigned?

  2. 2.What is typeof null?

  3. 3.Given const list = [1, 2];, what does list.push(3); do?

Finished reading?

Mark this lesson complete to track your progress.