Skip to content

Interview PrepBasics · Basics

Types, Equality and Coercion ​

32. What are the data types in JavaScript? ​

The short answer

JavaScript has seven primitive types: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object, including arrays, functions, dates, maps and plain objects. Primitives are immutable and compared by value; objects are mutable and compared by reference, so two objects with the same contents are still not equal unless they are the same object.

TypeExampleNotes
string'Corner Shop'Immutable text
number42, 3.14, NaN, InfinityOne type for integers and decimals, 64-bit floating point
bigint9007199254740993nWhole numbers of any size (question 40)
booleantrue, false
undefinedundefined"No value was given"
nullnull"Deliberately empty"
symbolSymbol('id')Unique keys (question 28)
object{}, [], new Date(), functionsEverything that is not a primitive

By value versus by reference:

ts
let a = 'tea'
let b = a
b = 'coffee'
console.log(a)                 // 'tea': strings are copied

const cartA = { items: 2 }
const cartB = cartA
cartB.items = 9
console.log(cartA.items)       // 9: both names point at one object

console.log({ items: 2 } === { items: 2 })   // false: two different objects

Primitives are immutable. String methods never change a string; they return a new one. 'abc'.toUpperCase() gives 'ABC' and leaves the original alone.

Primitives still have methods, such as 'abc'.length, because the engine wraps them in a temporary object for the call. You never need to create new String('abc'), and you should not: a wrapper object behaves like an object in comparisons.

33. What is the difference between == and ===? ​

The short answer

===, strict equality, is true only when both values have the same type and the same value; it never converts anything. ==, loose equality, first converts the values to a common type if their types differ, using a set of coercion rules, and then compares them. That conversion causes surprises such as '' == 0 being true. Use === everywhere; the one common exception is x == null, which checks for both null and undefined at once.

Expression=====Why == says so
5 == '5'truefalseThe string becomes the number 5
0 == ''truefalse'' becomes 0
0 == '0'truefalse'0' becomes 0
'' == '0'falsefalseBoth strings, compared as text
false == '0'truefalseBoth become 0
null == undefinedtruefalseA special rule
null == 0falsefalsenull only loosely equals undefined
NaN == NaNfalsefalseNaN equals nothing (question 38)

The first rows show the problem: 0 == '' and 0 == '0' are both true, but '' == '0' is false. Loose equality is not even consistent with itself.

The == null idiom:

ts
function shippingLabel(address?: string | null) {
  if (address == null) return 'Collect in store'    // true for null and undefined only
  return `Deliver to ${address}`
}

It reads well and is precise, because == null matches exactly null and undefined, not 0, '' or false. Many teams still prefer address === null || address === undefined, or address ?? …, for clarity.

For objects, both operators compare references: two different objects are never equal, however alike they look. To compare contents, compare the fields you care about, or use a deep equality helper.

Object.is is a third option. It is like === except that Object.is(NaN, NaN) is true and Object.is(0, -0) is false.

34. What are the differences between null and undefined? ​

The short answer

undefined means a value was never set: an uninitialised variable, a missing property, a missing argument, or a function with no return. null means "deliberately empty", and is something a programmer assigns on purpose. They are loosely equal (null == undefined) but not strictly equal, and typeof null returns 'object', which is a long-standing bug in the language.

Where each one comes from:

ts
let couponCode                               // undefined: declared, never set
const order = { id: 'A12' }
order.discount                               // undefined: property does not exist

function findCustomer(id: string) {}         // no return
findCustomer('c1')                           // undefined

const deliveredAt: Date | null = null        // null: we know there is no date yet
undefinednull
MeaningNot setSet to "nothing" on purpose
Set byThe engine, by defaultYou
typeof'undefined''object', a historical bug
In JSONProperty is droppedKept as null
Default parametersTrigger the defaultDo not trigger the default
Number conversionNaN0

Two behaviours that matter in practice:

ts
function applyDiscount(price: number, rate = 0.1) { return price * (1 - rate) }

applyDiscount(100, undefined)   // 90: undefined uses the default
applyDiscount(100, null as any) // 100: null is a real value, treated as 0

JSON.stringify({ a: undefined, b: null })   // '{"b":null}'

In APIs, this difference carries meaning. In a PATCH request, a field that is missing usually means "leave it alone", while a field set to null means "clear it". Your validation must keep the two apart.

?? and ?. treat both the same way, as "nothing here" (question 42).

35. What are truthy and falsy values? ​

The short answer

When a value is used where a boolean is expected, such as in an if, it is converted to true or false. Exactly eight values are falsy: false, 0, -0, 0n, '', null, undefined and NaN. Every other value is truthy, including '0', 'false', [], {} and every function. The trap is treating a real value like 0 or an empty string as "missing".

FalsyTruthy surprises
false, 0, -0, 0n'0', 'false', ' ' (a space)
''[], an empty array
null, undefined{}, an empty object
NaNnew Boolean(false), a wrapper object

The classic bug:

ts
function itemsLabel(count?: number) {
  if (!count) return 'unknown'                  // (1) wrong
  return `${count} items`
}
itemsLabel(0)         // 'unknown': but 0 is a real count

function itemsLabelFixed(count?: number) {
  if (count === undefined) return 'unknown'     // (2) right
  return `${count} items`
}
  1. !count is true for 0, so an empty cart is reported as unknown.
  2. Check for the specific "missing" value instead.

The same trap with ||:

ts
const qty = input.qty || 1      // 0 becomes 1: wrong
const qty2 = input.qty ?? 1     // only null or undefined become 1: right

?? exists precisely to fix this (question 42).

Checking an empty array must look at its length, because the array itself is truthy: if (items.length === 0), not if (!items).

36. What is type coercion? ​

The short answer

Type coercion is JavaScript automatically converting a value from one type to another when an operation needs it, such as turning a string into a number for subtraction. It happens implicitly with operators like +, -, == and in if conditions, and explicitly when you call Number(), String() or Boolean(). The biggest trap is +, which concatenates if either side is a string, while the other arithmetic operators convert to numbers.

The + trap, with values from a form, which are always strings:

ts
const qty = '2'          // from an <input>
const price = 5

qty + price              // '25': string concatenation
qty * price              // 10: * converts to numbers
qty - price              // -3
Number(qty) + price      // 7: convert explicitly first

The rules, simplified:

OperationConverts to
+ with any stringString, then concatenate
-, *, /, %, <, >Number
if, !, &&, `
== with different typesUsually number (question 33)
Template literal ${x}String

Objects are converted by calling valueOf and then toString, which gives famous oddities:

ts
[] + []      // '': both become empty strings
[] + {}      // '[object Object]'
[1, 2] + 3   // '1,23'

Nobody writes this on purpose. Interviewers ask about it to see whether you know that + prefers strings.

Number conversion pitfalls:

ExpressionResult
Number('')0
Number(' 42 ')42
Number('42px')NaN
parseInt('42px', 10)42: reads digits until it stops
Number(null)0
Number(undefined)NaN

The habit that avoids all of it: convert explicitly at the boundary, where data enters your program, validate it, and use === everywhere else. TypeScript then catches most accidental mixing of types before the code runs.

37. Why is 0.1 + 0.2 not equal to 0.3? ​

The short answer

JavaScript numbers are 64-bit binary floating-point values, the IEEE 754 standard used by most languages. Many decimal fractions, such as 0.1 and 0.2, cannot be written exactly in binary, just as one third cannot be written exactly in decimal. So each is stored as the nearest possible value, and the tiny errors add up: 0.1 + 0.2 gives 0.30000000000000004. For money, store whole units such as pence or cents as integers, or use a decimal library.

The analogy. In decimal, one third is 0.3333… for ever. If you can only keep a few digits, you round it, and 1/3 + 1/3 + 1/3 gives 0.9999 instead of 1. Binary has the same problem with tenths: 0.1 in binary is 0.0001100110011…, repeating for ever, so it gets rounded.

ts
console.log(0.1 + 0.2)              // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3)      // false

Comparing decimals safely:

ts
function nearlyEqual(a: number, b: number) {
  return Math.abs(a - b) < Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b))
}
nearlyEqual(0.1 + 0.2, 0.3)          // true

Number.EPSILON is the gap between 1 and the next number JavaScript can represent, about 2.2 × 10⁻¹⁶.

Money, the important case:

ts
// Wrong: floating-point pounds
const total = 19.99 * 3                   // 59.97000000000001

// Right: integer pence
const priceInPence = 1999
const totalPence = priceInPence * 3       // 5997, exact
const display = (totalPence / 100).toFixed(2)   // '59.97', only for display

Store and calculate in the smallest unit as integers, and only convert to pounds for display. For rates and divisions, such as tax splits, a decimal library such as decimal.js, or a numeric column in the database, avoids rounding surprises.

Other number limits worth knowing:

LimitValue
Largest safe integer, Number.MAX_SAFE_INTEGER9,007,199,254,740,991, about 9 × 10¹⁵
Beyond itIntegers lose precision: use BigInt (question 40)
toFixedReturns a string, and itself rounds a binary value

38. What is NaN, and how do you check for it? ​

The short answer

NaN, "not a number", is the number value produced by a failed numeric operation, such as Number('abc') or 0 / 0. Its type is number, and it is the only value not equal to itself, so NaN === NaN is false. Check for it with Number.isNaN(x), which is true only for NaN itself; avoid the old global isNaN, which converts its argument first and returns true for strings like 'hello'.

ts
const qty = Number('two')            // NaN
typeof qty                           // 'number'
qty === NaN                          // false: NaN equals nothing
Number.isNaN(qty)                    // true: the right check

isNaN('hello')                       // true: converts 'hello' to NaN first
Number.isNaN('hello')                // false: 'hello' is not the NaN value

NaN spreads. Any arithmetic with NaN gives NaN, so one bad input silently poisons a whole calculation:

ts
const total = 20 + Number(undefined) * 2     // NaN

That is why validation at the input boundary matters: reject the bad value where it enters, instead of finding NaN in a report a week later.

Related checks:

CheckTrue for
Number.isNaN(x)Only NaN
Number.isFinite(x)Real numbers, not NaN or Infinity
Number.isInteger(x)Whole numbers
Number.isSafeInteger(x)Whole numbers within the safe range

Number.isFinite(x) is often the check you actually want for "is this a usable number".

39. What are the quirks of typeof? ​

The short answer

typeof returns a string naming a value's type, and it works even on undeclared variables without throwing. It has two famous quirks: typeof null is 'object', a bug kept for compatibility since the first version of JavaScript, and typeof [] is also 'object', because arrays are objects. Functions get their own answer, 'function'. Use Array.isArray for arrays and === null for null.

ExpressionResult
typeof 'tea''string'
typeof 42, typeof NaN'number'
typeof 10n'bigint'
typeof true'boolean'
typeof undefined'undefined'
typeof notDeclaredAnywhere'undefined', no error
typeof Symbol()'symbol'
typeof null'object': the bug
typeof [], typeof {}, typeof new Date()'object'
typeof function () {}, typeof class {}'function'

Reliable checks for each case:

ts
Array.isArray(value)                       // arrays
value === null                             // null
value instanceof Date                      // dates, within one realm
typeof value === 'object' && value !== null   // any non-null object
Object.prototype.toString.call(value)      // '[object Date]', '[object Array]', ...

Why typeof null is 'object'. In the first implementation, values carried a small type tag, and the tag for objects was zero. null was represented as the null pointer, also all zeros, so it read as an object. Fixing it would break existing websites, so it stays.

instanceof versus typeof: typeof is for primitives. instanceof checks whether a class's prototype is on an object's chain (question 23), so it works for your own classes: err instanceof PaymentError.

40. What is BigInt and when do you need it? ​

The short answer

BigInt is a numeric type for whole numbers of any size, written with an n suffix such as 9007199254740993n, or created with BigInt('…'). Normal numbers can only represent integers exactly up to about 9 × 10¹⁵. Beyond that they silently lose precision. Use BigInt for very large IDs, such as 64-bit database or Twitter-style IDs, cryptography and exact large counters. BigInts cannot be mixed with normal numbers in arithmetic without an explicit conversion.

The precision problem:

ts
const fromDb = 9007199254740993          // a 64-bit order ID
console.log(fromDb)                      // 9007199254740992: silently wrong

const exact = 9007199254740993n
console.log(exact)                       // 9007199254740993n
console.log(exact + 1n)                  // 9007199254740994n

Rules to know:

RuleExample
No mixing with numbers10n + 1 throws TypeError
Convert explicitly10n + BigInt(1), or Number(10n) + 1
Division drops the fraction7n / 2n is 3n
No Math functionsMath.max(1n, 2n) throws
JSON does not support itJSON.stringify({ id: 1n }) throws

The JSON problem in APIs. A 64-bit ID sent as a JSON number loses precision as soon as JavaScript parses it, and JSON.stringify cannot write a BigInt at all. The common solution is to send large IDs as strings: {"orderId": "9007199254740993"}. Most APIs that use 64-bit IDs do exactly this.

Database drivers often have an option to return 64-bit integer columns as strings or BigInts for the same reason, such as the pg driver's type parsers for bigint columns.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet