Tuesday, October 18, 2011

JavaScript: Types and values

Working on other's codes is like walking in a huge cellar with a bunch of old boxes: you always find some interesting things. I write about types today.

Let's work with the following variables:

var point = function() {
    this.x = 4;
    this.y = 6;
}

// var v0; Note: I commented it out with purpose to make it undefined.   
var v1;
var v2 = null;
var v3 = false;
var v4 = 'some text';
var v5 = 68;
var v6 = {};
var v7 = new point();
var v8 = new Array();
var v9 = function() {};

How can you determine the type of each variable? Use the typeof operand. It returns a string representation of the operand's type. Let's see the types of the variables above:

typeof v0; // undefined
typeof v1; // undefined
typeof v2; // object
typeof v3; // boolean
typeof v4; // string
typeof v5; // number
typeof v6; // object
typeof v7; // object
typeof v8; // object
typeof v9; // function

Look at the result of v0 and v1. Why do they have the same undefined type? v0 is not declared, it's obvious why it is undefined. But v1? Because it is not defined (just like the type tells to us)! We stated that there is a variable called v1 but we didn't give it a value.

Did you notice that v2 with null assigned to it is an object type? Yes, you see it well. As I know, the reason for this is that the null type is a special object in JavaScript.

Common mistake with types


Typeof

I see the following comparison many times in codes I meet:
if(typeof v0 === undefined) {
    alert('not executed! hah!');
}

The alert function call won't run because the comparison in the if statement is wrong. As said before, typeof returns a string, but right now it is matched against an undefined value. It won't even work with the 'equal to' operator. Let's correct it:
if(typeof v0 === 'undefined') {
    alert('executed! hah!');
}

So now, the return value of typeof is compared to a string.

Null values

Another confusion rises when comparing undefined but declared variables against null value.
var v1;

if(v1 == null) {
    // it will run
    alert('yep');
}

if(v1 === null) {
    // it won't run
    alert('nope');
}

With the 'equals to' operator, JavaScript does type casting and evaluates the v1 variable with null value. But in the second case, with the 'exactly equals to' operator, the undefined value is kept because the operator checks the value and the type too.

Infinity and NaN

Take into account that type of a variable with Infinity or NaN value is number:
var v10 = 1000 / 0; // Infinity
var v11 = 1000 / 'book'; // NaN

typeof v10; // number
typeof v11; // number


I hope you also found it interesting. :)

No comments:

Post a Comment