Why is an empty string in JavaScript equals to zero?

56 Views Asked by At

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?

1

There are 1 best solutions below

3
Alexander Nenashev On

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 criteria

My guess since '' is falsy, it's convertible to false which is easily expressed as 0. I guess Number(' ') looks more weird btw but that's what we have in the language's specification ‍♂️:

console.log(Number(' '))

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:

console.log(NaN == NaN);

At least all those quirks are well known and documented.