type conversion

Matthias Reuter's picture

All about types in Javascript - Explicit type conversion

This is the third part of a series "All about types" in Javascript.

  1. The basics - types and general rules of conversion
  2. Automatic type conversion
  3. Explicit type conversion
  4. Type detection

Explicit type conversion

When I wrote about automatic type conversion I told my story of testing if "0" really converts to true, which I did by comparison to true. That was wrong, as I found out, but what is the right way? One possibility is

if ("0") {
  alert("true");
}
else {
  alert("false");
}
Read more

Matthias Reuter's picture

All about types in Javascript - Automatic type conversion

This is the second part of a series "All about types" in Javascript.

  1. The basics - types and general rules of conversion
  2. Automatic type conversion
  3. Explicit type conversion
  4. Type detection

Automatic type conversion

You have seen it before:

var element = document.getElementById("someId");
if (element) {
  // do something
}

That's an automatic type conversion. The if-statement expects a boolean value, and if the given expression does not return one, the result is converted. document.getElementById either returns an object or null. Null is converted to false, any object to true. That's why constructions as the above work.Read more

Matthias Reuter's picture

All about types in Javascript - The basics

Javascript is a loosely typed language. That means a variable x may now hold a number, two lines down a string and another ten lines down an HTML element. What might be confusing is that Javascript often converts types automatically. The rules behind automatic type convertion sometimes are - well, surprisingly abnormal. Did you know that

"0" == false

evaluates to true and why?

Programmers from other languages such as Java often find dynamic typing challenging, and therefore try to twist Javascript to help avoid typing problems like that:

function isString(obj) { return typeof(obj) == 'string'; }
function isNumber(obj) { return typeof(obj) == 'number'; }
function isBoolean(obj) { return typeof(obj) == 'boolean'; }
function isFunction(obj) { return typeof(obj) == 'function'; }
function isObject(obj) { return typeof(obj) == 'object' || isFunction(obj); }
Read more

Syndicate content