Question Bank
JavaScript `typeof`, NaN, and Number Quirks Traces
Difficulty: Easy
Six traces covering the `typeof` chain, `isNaN` vs `Number.isNaN`, `parseInt` with `map`, the comma operator, `Object.is`, and `Number()` vs `new Number()`.
JavaScript `typeof`, NaN, and Number Quirks Traces
Six traces covering the `typeof` chain, `isNaN` vs `Number.isNaN`, `parseInt` with `map`, the comma operator, `Object.is`, and `Number()` vs `new Number()`.
295 views
3
What does the following code print, and why?
Examples
Example 1:
Input: console.log(typeof typeof 1)
Output: string
Explanation: Inner typeof 1 returns the string 'number', and typeof applied to any string is always 'string'.What does each line print? Why does isNaN([]) return false?
Examples
Example 1:
Input: isNaN([]); isNaN({}); isNaN('22'); isNaN('abc'); isNaN(NaN); NaN === NaN
Output: false; true; false; true; true; false
Explanation: Global isNaN coerces its argument to a number first, and NaN === NaN is always false by spec which is why Number.isNaN exists.What does the following code print, and why is the result NOT [0, 5, 10]?
Examples
Example 1:
Input: console.log(['0', '5', '10'].map(parseInt))
Output: [0, NaN, 2]
Explanation: map passes (value, index) so parseInt receives the index as the radix, giving radix 0 then 1 (invalid) then 2 (binary).What does the following code print, and how does the comma operator pick a value?
Examples
Example 1:
Input: getNumber()
Output: 3
Explanation: The parentheses group a single comma-operator expression that evaluates each operand left to right and yields the last value.What does each comparison print? In which cases does Object.is disagree with ===?
Examples
Example 1:
Input: same('bar', 'bar'); same(null, 0); same(NaN, NaN); same(true, 1); same(false, !!0); same({a:1}, {a:1})
Output: true; false; true; false; true; false
Explanation: Object.is matches === except it treats NaN as equal to NaN and treats +0 as different from -0, while object literals still compare by reference.What does each log print, and why does b === c return false?
Examples
Example 1:
Input: typeof a; typeof b; typeof c; a === b; b === c
Output: number; number; object; true; false
Explanation: Number(x) without new returns a primitive while new Number(x) returns a wrapper object, and === between a primitive and a wrapper is always false.