I understand the concepts of type coercion and type conversion, but they don't clarify why an empty string is zero. Not NaN, but zero.
console.log(Number('')) // 0
The only explanation I was able to found is that an empty string is a part of falsy values, but it covers only a boolean context.
This MDN docs page states "an empty string is zero" as a fact, as well as Language Specification (if I get it right).
Is there a rationale or deeper meaning for such behavior?
JS is a very loose typed language, so when when 2 different types meet in a math expression JS tries very hard to coerce them into numbers even it could look weird.
An example when we can use
-operator to use string and boolean types directly as numbers: I want to sort an array with multiple criteriaMy guess since
''is falsy, it's convertible tofalsewhich is easily expressed as0. I guessNumber(' ')looks more weird btw but that's what we have in the language's specification ♂️:I guess it's here: https://tc39.es/ecma262/multipage/abstract-operations.html#sec-runtime-semantics-stringnumericvalue.
Languages like JS and PHP initially were for just adding a bit of interactivity and conditional rendering to web pages, so preserved some quirks historically for backward compatibility (you cannot change a spec and ruin WWW) like
NaN == NaN:At least all those quirks are well known and documented.