Types and Coercion
JavaScript has no static types at runtime, so every value carries its own type and the engine converts between them implicitly. Interviewers probe this constantly because coercion is where the language's most famous surprises live, alongside the operators and statement forms that trip people up when they read code.
part ofJavaScriptread it →on this pageshowhide
explore
- Primitives and Objects13 questions
- The Seven Primitive Types5 questions
- Wrapper Objects and Autoboxing4 questions
- Runtime Type Detection4 questions
- Equality and Conversion18 questions
- Loose Equality and the == Algorithm5 questions
- ToPrimitive, valueOf, and toString5 questions
- Truthy, Falsy, and ToBoolean4 questions
- Numbers and Numeric Types15 questions
- IEEE-754 Floats and Precision5 questions
- NaN, Infinity, and Negative Zero5 questions
- Safe Integers and BigInt5 questions
- Strings and Symbols15 questions
- Template Literals and Tagged Templates5 questions
- String Immutability and UTF-165 questions
- Symbols and Well-Known Symbols5 questions
- Bitwise and Unary Operators5 questions
- Statement and Parsing Hazards6 questions
questions
72 · 6 sectionsIn JavaScript, what does the typeof operator return for null, for an array, for a function or class, and for a variable that was never declared?
basics
~20 stypeof null returns "object" — a historic bug kept for compatibility. Arrays return "object" too, so typeof cannot spot them. Functions and classes return "function". typeof on a never-declared name safely returns "undefined" instead of throwing.
Name the seven primitive types in JavaScript and explain what makes a value a primitive rather than an object.
basics
~10 sJavaScript has seven primitives: string, number, boolean, null, undefined, symbol and bigint. Everything else is an object. Primitives are immutable, hold no properties of their own, and are copied and compared by their value.
An array built inside an iframe is handed to the parent page, where value instanceof Array evaluates to false even though the value genuinely is an array. Why does instanceof fail here, and what check works instead?
basics
~20 sEach iframe is a separate realm with its own Array constructor and Array.prototype, so a foreign array's prototype chain never reaches the parent's Array.prototype and instanceof is false. Array.isArray reads the internal array brand and works across realms.
In JavaScript, how does assigning a primitive to another variable differ from assigning an object, and what does that mean for a value you pass into a function?
basics
~20 sAssignment always copies a value. For a primitive that value is the data itself, so the two variables are independent. For an object the value is a reference, so both names point at one object and a mutation through either is visible through both.
In JavaScript, what is the difference between null and undefined, and why does a default parameter value apply when an argument is undefined but not when it is null?
basics
~20 sundefined is the absence the language itself produces: unassigned variables, missing arguments, missing properties, functions with no return. null is an absence a programmer assigns deliberately. Default parameter values fire only for undefined, never for null.
In JavaScript, what does the == (loose equality) operator do that === does not, and what do '5' == 5 and '5' === 5 each evaluate to?
basics
~20 sThe == operator converts operands to a common type before comparing; === requires matching types and never converts. So '5' == 5 is true, because the string is converted to the number 5, while '5' === 5 is false.
In JavaScript, what does the strict equality operator === compare, and how does it behave when its two operands have different types?
basics
~20 s=== returns true only when both operands have the same type and the same value. Different types are never converted, so the result is immediately false. Objects and arrays compare by reference, not by contents.
In JavaScript, why does '5' + 3 give '53' while '5' - 3 gives 2? Explain what the + operator does with mixed operand types.
basics
~20 sBinary + is the only arithmetic operator that is also string concatenation: after converting both operands to primitives, if either one is a string it concatenates, otherwise it adds numerically. Every other arithmetic operator converts to number unconditionally, so '5' - 3 is 2.
In JavaScript, which values are falsy — that is, which convert to false when used as an `if` condition — and which commonly-assumed-falsy values are actually truthy?
basics
~20 sJavaScript has a fixed falsy list: false, 0, -0, 0n, the empty string, null, undefined, and NaN. Every other value is truthy — including '0', 'false', the empty array, the empty object, and every function.
In JavaScript, the expression '0' == false evaluates to true. Walk through the loose-equality conversion steps that produce that result.
basics
~20 sA boolean operand is converted to a number first, so false becomes 0 and the comparison becomes '0' == 0. The string is then converted with ToNumber to 0, so 0 == 0 is true. Booleans are never compared as booleans.
In JavaScript, why does `0.1 + 0.2 === 0.3` evaluate to false, and what does `0.1 + 0.2` actually produce?
basics
~10 sJavaScript numbers are IEEE-754 binary doubles, and 0.1, 0.2 and 0.3 cannot be written exactly in binary. The stored approximations add up to 0.30000000000000004, a different double from 0.3, so === is false.
In JavaScript, why does NaN === NaN evaluate to false, and how do you reliably test whether a value is NaN?
basics
~10 sNaN is the only JavaScript value not equal to itself: IEEE-754 makes every comparison involving NaN false, so === and indexOf never find it. Test with Number.isNaN(x), which checks the value without converting it.
How should you compare two computed JavaScript numbers for approximate equality, and what does `Number.EPSILON` actually represent?
basics
~20 sNumber.EPSILON is the gap between 1 and the next representable double, about 2.22e-16 — a relative spacing near 1, not a universal error bound. Compare with a tolerance scaled to the operands' magnitude, not a fixed epsilon.
In JavaScript, why does the expression 9007199254740993 === 9007199254740992 evaluate to true, and what does Number.MAX_SAFE_INTEGER have to do with it?
basics
~20 sA JavaScript number carries 53 bits of significand, so integers above 2^53 can no longer all be represented; the literal 9007199254740993 rounds to 9007199254740992 at parse time. Number.MAX_SAFE_INTEGER, 2^53 - 1, marks the last integer whose successor is still distinct.
How do JavaScript's global isNaN() and isFinite() differ from Number.isNaN() and Number.isFinite(), and which would you use to validate a numeric field?
basics
~10 sThe global isNaN and isFinite convert their argument to a number first, so isNaN("") is false and isFinite("100") is true. The ES2015 Number.isNaN and Number.isFinite never convert: any non-number returns false.
In JavaScript, what happens when you assign to a character position of a string, as in `let s = 'hello'; s[0] = 'H';`, and what does that tell you about how string methods behave?
basics
~20 sJavaScript strings are immutable, so the assignment silently does nothing in sloppy mode and throws a TypeError in strict mode; s stays "hello". Every string method, such as toUpperCase or trim, returns a brand-new string instead of editing the original.
In JavaScript, what is a Symbol, and what does using a symbol as an object property key give you that a string key does not?
basics
~20 sA Symbol is a primitive whose every value is unique: Symbol('id') never equals another Symbol('id'). Used as a property key, it cannot collide with any string key or with symbols created by other code, even when the descriptions match.
In JavaScript, what is a template literal (a string written in backticks), and how does it differ from building the same string with the + operator?
basics
~20 sA template literal is a backtick-delimited string that embeds any expression with ${...} and keeps newlines exactly as typed. Interpolated values are converted to strings automatically, so it produces what + would for most inputs, with far less quote juggling.
Why does `'🙂'.length` evaluate to 2 in JavaScript, and how do you count what a user would call one character?
basics
~20 sJavaScript's .length counts UTF-16 code units, not characters. The 🙂 emoji sits above the Basic Multilingual Plane, so it is stored as a two-unit surrogate pair. Iterating the string, for example with [...str], walks whole code points and yields 1.
When you call a JavaScript tagged template such as tag`a${x}b`, what arguments does the tag function actually receive, and what is the relationship between them?
basics
~20 sThe tag function receives the static text chunks as its first argument — an array with a raw property holding the unescaped text — followed by one argument per interpolated value. The chunks array always has exactly one more element than the number of values.
In JavaScript, how does `delete obj.k` differ from `obj.k = undefined`, and what does `delete` return?
basics
~20 sdelete removes the property, so the key leaves the in check and Object.keys, while assigning undefined keeps the key holding that value. delete returns true except on an own non-configurable property: false in sloppy code, a TypeError in strict.
In JavaScript, what does `return log(x), x * 2;` return, and how does the comma operator differ from the commas in `f(a, b)`?
basics
~20 sreturn log(x), x * 2 calls log(x), discards its result and returns x * 2. The comma operator runs operands left to right and yields the last; commas in argument lists and declarations are only separators.
In JavaScript, what do `void 2 === "2"` and `2 ** 3 ** 2` evaluate to, and why is `-2 ** 2` a SyntaxError?
basics
~20 svoid 2 === "2" is false because void binds first, so undefined is compared with "2". 2 ** 3 ** 2 is 512 because ** is right-associative. -2 ** 2 is rejected as ambiguous, so the grouping must be parenthesized.
In JavaScript, what do `x | 0` and `~~x` do to `7.9`, `-7.9`, `3000000000` and `NaN`, and why are they unsafe as truncation?
basics
~20 sx | 0 and ~~x both apply ToInt32: 7.9 becomes 7, -7.9 becomes -7, 3000000000 wraps to -1294967296 and NaN becomes 0. They are unsafe because values outside the signed 32-bit range wrap silently and bad input turns into 0.
In a JavaScript review, `(a << 24) | (b << 16) | (c << 8) | d` packs an IPv4 address: why do addresses from 128.0.0.0 up come out negative, and how do you fix it?
basics
~20 sShifts and OR return signed 32-bit integers, so when the first octet reaches 128 the top bit becomes the sign bit and the value reads as negative. Apply >>> 0 last to reinterpret those same bits as unsigned.
In JavaScript, how does a switch statement compare its value against each case, and what runs after a matching case that has no break?
basics
~20 sA JavaScript switch compares with strict equality and jumps to the first matching case. Without a break, execution keeps running the following clauses, default included, until a break or the end of the switch, whatever their values are.
In JavaScript, why does a function return undefined when the object literal after return starts on the next line, and how do you fix it?
basics
~20 sAutomatic semicolon insertion ends the statement: the grammar forbids a line break between return and its expression, so the parser reads a bare return and the next line never runs. Start the expression on the return line.
In JavaScript, what is the difference between encodeURI and encodeURIComponent, and which do you use for a value placed inside a query string?
basics
~20 sencodeURI is for an already assembled URL and leaves URL syntax such as / ? & = # alone. encodeURIComponent also escapes those characters, so it is the one for a single dynamic value such as a query parameter.
In JavaScript, why does parseInt read the page parameters `2abc` as 2 and `1e3` as 1, and how does Number differ?
basics
~20 sparseInt reads digits from the start and silently stops at the first invalid character, so 2abc gives 2 and 1e3 gives 1. Number converts the whole string or returns NaN, giving NaN and 1000 here.
A JavaScript file written without semicolons starts throwing `TypeError: x is not a function` right after someone adds a line beginning with `(`; why does that happen, and how do you stop it recurring?
basics
~20 sNo semicolon is inserted, because a line starting with ( can legally continue the previous expression as a call. Insertion needs an offending token or a restricted production. Prefix such lines with a semicolon, and enforce it with a linter.