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 ifgetElementById(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 whynull 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.
| Value | String | Number | Boolean | Object |
|---|---|---|---|---|
| Undefined value | "undefined" | NaN | false | chyba (error) |
null | "null" | 0 | false | chyba (error) |
| Nonempty string | Unchanged | The string’s numeric value or NaN | true | String object |
| Empty string | Unchanged | 0 | false | String object |
0 | "0" | Unchanged | false | Number object |
NaN | "NaN" | Unchanged | false | Number object |
| Infinity | "Infinity" | Unchanged | true | Number object |
| Negative infinity | "- Infinity" | Unchanged | true | Number object |
| Any other number | The number expressed as a string | Unchanged | true | Number object |
true | "true" | 1 | Unchanged | Boolean object |
false | "false" | 0 | Unchanged | Boolean object |
| Object | The result of calling toString() | The result of calling valueOf or toString(), or NaN | true | Unchanged |
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio