📎 Webclip
Stranger Things, JavaScript Edition
The post walks through a set of JavaScript expressions that produce unexpected results and explains them by pointing to how the language handles callback arguments, coercion, equality, and arithmetic. It shows that the odd outputs are not random, but follow JavaScript’s built-in rules.
Reading notes#
['1', '7', '11'].map(parseInt)returns[1, NaN, 3]becausemap()passes the value, the index, and the array to the callback, andparseInt()treats the index as the radix.- The expected result can be restored by passing only the current value to
parseInt. - The expression
('b'+'a'+ + 'a' + 'a').toLowerCase()becomesbananabecause+ 'a'producesNaN, which is then concatenated into the string. - The
failexample is built from expressions that producefalseandfalseundefined, then selects letters from those strings. - JavaScript uses truthy and falsy values when a boolean is needed, and falsy values listed in the post are
0,-0,0n, empty strings,null,undefined, andNaN. - Loose equality on arrays can return
truein many cases because JS applies coercion, such as[] == '',[] == 0, and nested arrays compared to0or''. - In arithmetic, subtraction and addition can behave differently with strings, numbers, arrays, and objects because JS applies coercion rules before evaluating the operation.
{} + []is treated differently from[] + {}when written without parentheses because the first form is parsed as a code block followed by unary plus.
