Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an empty string in JavaScript equals to zero?

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?

like image 996
Azenon Avatar asked May 14 '26 05:05

Azenon


1 Answers

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.

like image 53
Alexander Nenashev Avatar answered May 16 '26 17:05

Alexander Nenashev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!