dagblog.
← Archive

Automatic type conversion in JavaScript


A conversation prompted this post. I was advising a colleague
about a particular JavaScript construct. I don’t remember the exact code anymore,
of course, but it looked something like this:

function acme(id){
foo = document.getElementById(id);
if(!foo){
.
.
}
.
.
}

In essence, the question was how foo would evaluate if
getElementById(id) returned null. In the example above,
null evaluates to false.

I told my colleague that if there was no element with that ID, the code
inside the if statement would run. Unfortunately I couldn’t give a very good answer about why
null is converted to false.

To explain this behavior, we have to start with JavaScript’s lack of static typing, or its dynamic typing.
In JavaScript we don’t have to declare a variable’s type in advance. The type matters
only in the execution context, where the variable is converted to the required type.
In our example a Boolean is expected, so null is dynamically converted
to false.

The following table describes automatic data type conversions
(David Flanagan, JavaScript: The Definitive Guide, Fourth Edition, ISBN 80–7226–626–8).
It shows how JavaScript converts one type to another.

ValueStringNumberBooleanObject
Undefined value"undefined"NaNfalsechyba (error)
null"null"0falsechyba (error)
Nonempty stringUnchangedThe string’s numeric value or NaNtrueString object
Empty stringUnchanged0falseString object
0"0"UnchangedfalseNumber object
NaN"NaN"UnchangedfalseNumber object
Infinity"Infinity"UnchangedtrueNumber object
Negative infinity"- Infinity"UnchangedtrueNumber object
Any other numberThe number expressed as a stringUnchangedtrueNumber object
true"true"1UnchangedBoolean object
false"false"0UnchangedBoolean object
ObjectThe result of calling toString()The result of calling valueOf or toString(), or NaNtrueUnchanged

Medium version

Related articles

Related CZ Podcast episodes