Lesson 1 of 12 · 9 min · Core language
JavaScript types, variables and coercion
What you will learn
- The JavaScript data types and how to check them
let,constandvar- 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
constby default; useletwhen the variable must change; avoidvar. conststops reassignment, not mutation: aconstarray or object can still be changed (const list = []; list.push(1);works).letandconstare block-scoped (limited to the{ }where declared);varis function-scoped (next lesson).- Accessing a
letorconstvariable before its declaration throws aReferenceError(the temporal dead zone). - Name variables in
camelCase, constants such asMAX_RETRIESin capitals, classes inPascalCase.
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 idiomvalue == null, which is true for bothnullandundefined.
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.2is0.30000000000000004. For money, work in integers (paise) or use a decimal library, and format withtoFixed(2)orIntl.NumberFormat. - Safe integers stop at
Number.MAX_SAFE_INTEGER(2^53 - 1); useBigIntbeyond that (order ids from some APIs!). You cannot mixBigIntandnumberin arithmetic. NaNis a number that is not equal to itself: useNumber.isNaN(x).- Integer division does not exist:
Math.floor(7 / 2)orMath.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, thenlet; nevervar. - Compare with
===; convert explicitly; use??and?.. - Do not trust
typeoffor arrays andnull. - 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 valid0or"". typeof nullas a check.- Believing a
constobject is frozen. - Adding strings and numbers from form inputs (
"2" + "3"is"23"). - Floating-point money.
- Comparing arrays or objects with
===.
Try it yourself
- Predict, then check in the console:
"10" - 1,"10" + 1,[] == false,null + 1,undefined + 1. - Rewrite a function that uses
==and||with===,??and?.. - Parse a form value
"1,250"to a number safely and detect bad input. - Show that changing a copied object changes the original, then fix it with spread and
structuredClone. - Add
0.1 + 0.2in the console and format a rupee amount withIntl.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.isArrayand=== null. - Use
constandlet; copy objects with spread orstructuredClone. - Prefer
===, convert explicitly, know the eight falsy values, use??and?.. - Beware floating-point numbers,
BigIntlimits and form values that are strings.
Going deeper
- MDN: JavaScript data types and data structures: the types in detail.
- MDN: Equality comparisons and sameness:
==,===andObject.is. - MDN: Truthy and falsy: the complete list.
- ECMAScript language specification: the formal definition of types and conversions.
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.