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()`.
Question Bank
Easy
JavaScript
6 questions
quiz
js-language
js-number-precision
fundamentals
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'.console.log(typeof typeof 1);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.console.log(isNaN([]));
console.log(isNaN({}));
console.log(isNaN('22'));
console.log(isNaN('abc'));
console.log(isNaN(NaN));
console.log(NaN === NaN);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).const res = ['0', '5', '10'].map(parseInt);
console.log(res);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.function getNumber() {
return (1, 2, 3);
}
const number = getNumber();
console.log(number);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.const same = (a, b) => Object.is(a, b);
console.log(same('bar', 'bar'));
console.log(same(null, 0));
console.log(same(NaN, NaN));
console.log(same(true, 1));
console.log(same(false, !!0));
console.log(same({ a: 1 }, { a: 1 }));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.let a = 1;
let b = Number(1);
let c = new Number(1);
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(a === b);
console.log(b === c);