Lesson 1 of 12 · 9 min · Core language

JavaScript types, variables and coercion

Covers: JavaScript (ECMAScript 2025) in current browsers and Node.js 22 or newer. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • The JavaScript data types and how to check them
  • let, const and var
  • Primitives versus objects, and what that means for copying and comparing
  • == versus ===, implicit coercion and truthy and falsy values
  • Number and string quirks that cause real bugs

In simple words

JavaScript is flexible about types: a variable can hold a number now and text later, and the language will quietly convert values to make an operation work, so "5" * 2 gives 10 but "5" + 2 gives "52". That flexibility is convenient and also the source of many famous surprises. Learning the rules once means you can predict the results instead of memorising odd examples.

Words to know

  • Primitive: a simple value such as a number, string or boolean, copied by value.
  • Object: a collection of properties, such as an array or function, handled by reference.
  • Coercion: the automatic conversion of a value from one type to another.
  • Truthy and falsy: values that count as true or false in a condition.

Types

JavaScript has seven primitive types and objects:

Type Example Notes
number 42, 3.14, NaN, Infinity one type for integers and decimals (64-bit floating point)
bigint 123n arbitrarily large integers
string "hello", 'hi', `hi ${name}` immutable text (UTF-16)
boolean true, false
undefined undefined a variable that has no value yet
null null an intentional "no value"
symbol Symbol("id") unique identifiers
object {}, [], function(){}, new Date() everything else

Check a type with typeof:

typeof 42            // "number"
typeof "hi"          // "string"
typeof undefined     // "undefined"
typeof null          // "object"   (a historic bug; check null with === null)
typeof []            // "object"   (use Array.isArray(value))
typeof (() => {})    // "function"
typeof 10n           // "bigint"

let, const and var

const price = 1200;          // cannot be reassigned
let count = 0;               // can be reassigned
count = count + 1;

var old = "avoid";           // function-scoped, hoisted, redeclarable: legacy
  • Prefer const by default; use let when the variable must change; avoid var.
  • const stops reassignment, not mutation: a const array or object can still be changed (const list = []; list.push(1); works).
  • let and const are block-scoped (limited to the { } where declared); var is function-scoped (next lesson).
  • Accessing a let or const variable before its declaration throws a ReferenceError (the temporal dead zone).
  • Name variables in camelCase, constants such as MAX_RETRIES in capitals, classes in PascalCase.

Primitives and objects

Primitives are copied by value; objects are copied by reference (the variable holds a pointer to the object):

let a = 5;
let b = a;
b = 10;
console.log(a);          // 5   (independent copies)

const x = { n: 1 };
const y = x;             // y points to the SAME object
y.n = 2;
console.log(x.n);        // 2

const copy = { ...x };           // shallow copy
const deep = structuredClone(x); // deep copy (modern browsers and Node)

Comparing objects compares references, not contents: {} === {} is false, [1] === [1] is false. To compare contents, compare the properties, or compare JSON.stringify output for simple data, or use a utility.

Equality: == versus ===

  • === (strict equality) compares value and type, with no conversion. Use it by default.
  • == (loose equality) converts types first, with complicated rules. Avoid it, except the idiom value == null, which is true for both null and undefined.
5 === "5"      // false
5 == "5"       // true   (the string is converted to a number)
0 == false     // true
"" == 0        // true
null == undefined   // true
null === undefined  // false
NaN === NaN    // false   (use Number.isNaN(x) or Object.is)

Coercion

JavaScript converts values automatically in several situations:

"5" + 2        // "52"   + with a string concatenates
"5" - 2        // 3      other arithmetic converts to numbers
"5" * "2"      // 10
true + 1       // 2
[] + {}        // "[object Object]"
Number("42px") // NaN
Number("")     // 0
parseInt("42px") // 42  (stops at the first non-digit)
String(123)    // "123"
Boolean("")    // false

To avoid surprises, convert explicitly at the boundary where data enters (form fields and URLs always give strings): Number(input.value), parseInt(text, 10), parseFloat(text), String(n), and check with Number.isNaN(result) or Number.isFinite(result). Template literals build strings clearly: `Total: ₹${total.toFixed(2)}`.

Truthy and falsy

In a condition (if, &&, ||, !, ? :), values are treated as true or false. Falsy values are exactly eight: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy, including "0", "false", [] and {}.

if ([]) console.log("an empty array is truthy");
const name = input || "Guest";       // || returns the first truthy operand: "" and 0 are replaced too
const count = input ?? 0;            // ?? (nullish coalescing) replaces only null and undefined
const city = user?.address?.city;    // ?. (optional chaining): undefined instead of an error

Use ?? instead of || when 0, "" or false are valid values. ??=, ||= and &&= assign conditionally.

Number quirks

  • All numbers are 64-bit floats: 0.1 + 0.2 is 0.30000000000000004. For money, work in integers (paise) or use a decimal library, and format with toFixed(2) or Intl.NumberFormat.
  • Safe integers stop at Number.MAX_SAFE_INTEGER (2^53 - 1); use BigInt beyond that (order ids from some APIs!). You cannot mix BigInt and number in arithmetic.
  • NaN is a number that is not equal to itself: use Number.isNaN(x).
  • Integer division does not exist: Math.floor(7 / 2) or Math.trunc.
  • Format for India: new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(125000) gives ₹1,25,000.00.

String basics

Strings are immutable sequences of UTF-16 code units: "hello".toUpperCase() returns a new string. Useful methods: slice, includes, startsWith, padStart, trim, split, replaceAll, at(-1), and localeCompare for sorting names (including Indian scripts) correctly. Emoji and some Indian characters use more than one code unit, so length is not the number of visible characters; use Intl.Segmenter when it matters.

Safe habits

  • Declare with const, then let; never var.
  • Compare with ===; convert explicitly; use ?? and ?..
  • Do not trust typeof for arrays and null.
  • Treat data from forms, URLs and APIs as untrusted strings: parse and validate.
  • Turn on a linter (ESLint) and use TypeScript (a later course) to catch type mistakes before running.

Common mistakes

  • Using == and relying on coercion.
  • Using || for defaults and replacing valid 0 or "".
  • typeof null as a check.
  • Believing a const object is frozen.
  • Adding strings and numbers from form inputs ("2" + "3" is "23").
  • Floating-point money.
  • Comparing arrays or objects with ===.

Try it yourself

  1. Predict, then check in the console: "10" - 1, "10" + 1, [] == false, null + 1, undefined + 1.
  2. Rewrite a function that uses == and || with ===, ?? and ?..
  3. Parse a form value "1,250" to a number safely and detect bad input.
  4. Show that changing a copied object changes the original, then fix it with spread and structuredClone.
  5. Add 0.1 + 0.2 in the console and format a rupee amount with Intl.NumberFormat.

Check yourself

What is the difference between == and ===?

=== compares value and type without conversion; == converts types first using complicated rules. Prefer ===.

What does const prevent?

Reassigning the variable. It does not make an object or array immutable.

What is the difference between || and ???

|| falls back on any falsy value (0, "", false); ?? falls back only on null or undefined.

How do you check whether a value is an array?

Array.isArray(value), because typeof [] is "object".

Interview questions

What are the primitive types in JavaScript?

string, number, bigint, boolean, undefined, null and symbol; everything else is an object.

Why is 0.1 + 0.2 !== 0.3 in JavaScript?

Numbers are binary floating-point, and 0.1 and 0.2 cannot be represented exactly, so the sum is slightly off. Use integers or compare with a tolerance.

What is type coercion and why is it dangerous?

Automatic conversion between types in operations and comparisons; the rules are subtle ("5" + 2 versus "5" - 2), so unintended conversions cause bugs. Use strict equality and explicit conversions.

Summary

  • Seven primitives plus objects; check with typeof, Array.isArray and === null.
  • Use const and let; copy objects with spread or structuredClone.
  • Prefer ===, convert explicitly, know the eight falsy values, use ?? and ?..
  • Beware floating-point numbers, BigInt limits and form values that are strings.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.