JavaScript values, types and operators
Every JavaScript program starts by putting values into variables and combining them with operators. This page covers that foundation in four steps: how to declare variables and which data types exist, how the operators work, what happens when JavaScript converts one type into another for you, and which values count as “true” or “false” in an if. These four ideas explain most of the “JavaScript is weird” surprises beginners hit, such as "10" + 3 giving "103" or an empty array passing an if check.
The samples follow a small invented shop called OrdersPortal. Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). Files ending in .mjs are ES modules, which always run in strict mode. The output shown under each sample was produced with Node.js 22.23.
Topics on this page
Section titled “Topics on this page”| Topic | What you learn |
|---|---|
| Variables and data types | const, let and var, the seven primitive types and objects, and typeof. |
| Operators | Arithmetic, comparison, logical and the newer ?? and ?. operators. |
| Type coercion | When JavaScript converts types implicitly and how to convert explicitly. |
| Truthy and falsy values | The fixed list of falsy values and how conditions use them. |
Variables and data types
Section titled “Variables and data types”A variable is a name bound to a value. Modern JavaScript (ES2015 and later) declares variables with const or let; the older var still works but has function scope and hoisting rules that cause bugs, so new code avoids it.
constcreates a binding you cannot reassign. Use it by default.letcreates a binding you can reassign, for counters, accumulators and values that change in a loop.- Both are block-scoped: they exist only inside the nearest
{ ... }.
const does not freeze the value. A const array can still have items pushed into it; you just cannot point the name at a different array.
JavaScript has eight data types. Seven are primitives, which are immutable values: string, number (one 64-bit floating-point type for integers and decimals), bigint (arbitrary-size integers, written 123n), boolean, undefined (a variable with no value yet), null (an intentional “no value”) and symbol (a unique key). Everything else is an object, including arrays, functions, dates and maps. The typeof operator tells you the type at run time, with two historical quirks: typeof null is "object", and functions report "function".
const shopName = "OrdersPortal";let openOrders = 3;openOrders = openOrders + 1; // let can be reassigned
const order = { id: "A-1001", total: 59.9, paid: false, coupon: null };const tags = ["gift", "express"];tags.push("fragile"); // allowed: const stops reassignment, not mutation
const samples = [shopName, openOrders, 59.9, 2n ** 64n, order.paid, order.coupon, undefined, Symbol("id"), order, tags, () => {}];for (const value of samples) { console.log(typeof value);}console.log(Array.isArray(tags), order.coupon === null);console.log(tags);Output:
stringnumbernumberbigintbooleanobjectundefinedsymbolobjectobjectfunctiontrue true[ 'gift', 'express', 'fragile' ]Pitfalls:
typeof nullis"object". Test for null withvalue === null, and for arrays withArray.isArray(value), because arrays also report"object".- Reassigning a
constthrows.TypeError: Assignment to constant variable.If the value needs to change, declare it withlet. - Numbers are floating point.
0.1 + 0.2is0.30000000000000004, and integers are exact only up toNumber.MAX_SAFE_INTEGER(2^53 - 1). Use whole cents for money andbigintfor very large integers.
Operators
Section titled “Operators”Operators combine values into new values. The groups you use every day are:
- Arithmetic:
+,-,*,/,%(remainder) and**(exponent, ES2016).++and--add or subtract one. - Assignment:
=plus shortcuts such as+=,*=and the logical assignments||=,&&=and??=(ES2021). - Comparison:
===and!==compare without converting types;==and!=convert first.<,>,<=and>=compare numbers, or strings by UTF-16 code unit order. - Logical:
&&,||and!.&&and||short-circuit and return one of their operands, not necessarily a boolean:a || breturnsaif it is truthy, otherwiseb. - Nullish coalescing
??(ES2020): returns the right side only when the left side isnullorundefined, so0and""are kept. - Optional chaining
?.(ES2020): reads a property only if the object exists; otherwise the whole expression isundefinedinstead of throwing. - Conditional (ternary):
condition ? valueIfTrue : valueIfFalse.
const order = { items: [{ price: 20, qty: 2 }, { price: 7.5, qty: 1 }], discount: 0, customer: null };
const subtotal = order.items[0].price * order.items[0].qty + order.items[1].price * order.items[1].qty;console.log("subtotal:", subtotal);console.log("items % 2:", order.items.length % 2, "| 2 ** 10:", 2 ** 10);
console.log("discount || 10:", order.discount || 10); // 0 is falsy, so the fallback winsconsole.log("discount ?? 10:", order.discount ?? 10); // 0 is kept: it is not null/undefined
console.log("customer email:", order.customer?.email); // no TypeErrorconsole.log("shipping:", subtotal >= 50 ? "free" : "standard");console.log("5 == '5':", 5 == "5", "| 5 === '5':", 5 === "5");console.log("'apple' < 'banana':", "apple" < "banana", "| '10' < '9':", "10" < "9");Output:
subtotal: 47.5items % 2: 0 | 2 ** 10: 1024discount || 10: 10discount ?? 10: 0customer email: undefinedshipping: standard5 == '5': true | 5 === '5': false'apple' < 'banana': true | '10' < '9': truePitfalls:
||replaces valid zeros and empty strings. For “use a default only when missing”, use??.- Comparing numeric strings.
"10" < "9"istruebecause strings compare character by character. Convert withNumber()first. - Mixing
??with||or&&.a ?? b || cis aSyntaxError; add parentheses to show which runs first.
Type coercion
Section titled “Type coercion”Type coercion is JavaScript converting a value from one type to another. It happens implicitly when an operator receives mismatched types, and explicitly when you call a conversion function yourself.
The rules that matter most:
+with a string on either side concatenates strings. Every other arithmetic operator (-,*,/,%,**) converts both sides to numbers.==converts operands before comparing.null == undefinedistrue, butnull == 0isfalse.===never converts, which is why style guides prefer it.- Explicit conversion is clearer:
Number(x),String(x)andBoolean(x).Number("")is0,Number("12px")isNaN, andparseInt("12px", 10)reads digits until the first non-digit and returns12. NaN(“not a number”) is the result of a failed numeric conversion. It is not equal to anything, including itself, so test it withNumber.isNaN(value).
Values from forms, URLs, environment variables and CSV files are always strings. Convert them once at the edge of your program and validate the result, then work with real numbers everywhere else.
const quantityFromForm = "3"; // form fields, query strings and env vars are stringsconst unitPrice = 12.5;
console.log("implicit +:", quantityFromForm + unitPrice);console.log("implicit *:", quantityFromForm * unitPrice);
function parseQuantity(text) { const qty = Number(text); if (!Number.isInteger(qty) || qty <= 0) { throw new RangeError(`Invalid quantity: "${text}"`); } return qty;}
console.log("explicit:", parseQuantity(quantityFromForm) * unitPrice);console.log(Number(""), Number(" 42 "), Number("12px"), parseInt("12px", 10));console.log("NaN === NaN:", NaN === NaN, "| Number.isNaN:", Number.isNaN(Number("abc")));console.log("null == undefined:", null == undefined, "| null == 0:", null == 0);
try { parseQuantity("two");} catch (error) { console.log(error.name + ":", error.message);}Output:
implicit +: 312.5implicit *: 37.5explicit: 37.50 42 NaN 12NaN === NaN: false | Number.isNaN: truenull == undefined: true | null == 0: falseRangeError: Invalid quantity: "two"Pitfalls:
+on form input concatenates."10" + 3is"103". Convert withNumber()before adding.Number("")is0. An empty field silently becomes zero; check for empty input before converting.isNaN()coerces first. The globalisNaN("abc")istruebecause it converts the string.Number.isNaN()only returnstruefor the actualNaNvalue.
Truthy and falsy values
Section titled “Truthy and falsy values”Conditions such as if, while, ! and the logical operators convert their operand to a boolean. The set of values that become false is fixed and short. MDN lists them as: false, 0, -0, 0n, "" (empty string), null, undefined and NaN (plus the browser-only legacy document.all). Every other value is truthy, including "0", "false", [], {} and any function.
This makes short checks such as if (customer) convenient for “does this object exist?”, but risky for numbers and strings where 0 or "" are valid data. When a check is about a specific condition, write it explicitly: items.length > 0, value !== undefined, typeof name === "string" && name.trim() !== "".
Boolean(value) and the double negation !!value both convert a value to true or false. Boolean(value) is easier to read.
const values = [false, 0, -0, 0n, "", null, undefined, NaN, "0", "false", [], {}, () => {}];const show = (v) => Object.is(v, -0) ? "-0" : typeof v === "bigint" ? `${v}n` : typeof v === "function" || v === undefined || Number.isNaN(v) ? String(v) : JSON.stringify(v);
for (const value of values) { console.log(`${show(value).padEnd(10)} -> ${Boolean(value)}`);}
const cart = { items: [], giftMessage: "", stockLeft: 0 };console.log("if (cart.items):", cart.items ? "runs" : "skipped");console.log("has items:", cart.items.length > 0);console.log("stock shown with ||:", cart.stockLeft || "unknown");console.log("stock shown with ??:", cart.stockLeft ?? "unknown");Output:
false -> false0 -> false-0 -> false0n -> false"" -> falsenull -> falseundefined -> falseNaN -> false"0" -> true"false" -> true[] -> true{} -> true() => {} -> trueif (cart.items): runshas items: falsestock shown with ||: unknownstock shown with ??: 0Pitfalls:
- Empty arrays and objects are truthy.
if (items)is true for[]; checkitems.length. 0and""are falsy. A quantity of0or an empty note is valid data, so do not treat it as “missing” with||."false"is truthy. A string from a query string or environment variable must be compared:flag === "true".
Choosing between them
Section titled “Choosing between them”| Situation | Prefer |
|---|---|
| A value that never gets reassigned | const |
| A counter or accumulator | let |
| Equality checks | === and !== |
| A default for a missing value | ?? (keeps 0 and "") |
| A default for any falsy value | || |
| Reading a property that may not exist | ?. |
| Turning input text into a number | Number() plus validation |
| Checking an array is not empty | array.length > 0 |
Interview questions
Section titled “Interview questions”1. What are JavaScript’s data types?
Seven primitives (string, number, bigint, boolean, undefined, null, symbol) and object. Arrays, functions and dates are objects. typeof reports "object" for null because of a bug kept for compatibility.
2. What is the difference between == and ===?
=== compares type and value without conversion. == applies the abstract equality algorithm, which converts operands first, so "5" == 5 and null == undefined are true. Use === except for a deliberate value == null check that matches both null and undefined.
3. Why does "5" + 3 give "53" but "5" - 3 give 2?
+ is both addition and string concatenation; if either operand is a string, it concatenates. - only does arithmetic, so it converts both operands to numbers.
4. What is the difference between || and ???
|| falls back for any falsy value, including 0, "" and false. ?? falls back only for null and undefined. Use ?? for defaults when 0 or an empty string is a valid value.
5. Senior scenario: a checkout bug report says “orders with quantity 0 are saved with quantity 1”. The code is const qty = Number(req.query.qty) || 1. What is wrong and how do you fix it?
Number("0") is 0, which is falsy, so || replaces it with 1. A missing parameter gives Number(undefined), which is NaN, and an empty one gives 0, so the code cannot tell “missing” from “zero” at all. Parse and validate explicitly: treat undefined as missing, convert with Number(), reject NaN and non-integers, and decide whether 0 is allowed by business rules, returning a 400 error instead of guessing.
Related pages
Section titled “Related pages”- Control flow, errors and async basics: the next step, using these values in conditions and loops.
- Block bindings: block scope, the temporal dead zone and choosing
let,constorvar. - Core language features:
??and?.in depth. - Logical assignment:
||=,&&=and??=. - BigInt: integers beyond
Number.MAX_SAFE_INTEGER. - Exponentiation operator:
**and its precedence rules.