Skip navigation

Some pretty stupid things in Javascript to follow.

Associative arrays are objects

Look at this interactive session (checkout Rhino or SpiderMonkey for a js shell)

js> var x = {}
js> x == {}
false
js> x == true
false
js> x == false
false

So, a condition

if({})

is always satisfied. There’s no native way to check if an associative array is empty! Because an associative array IS in fact an object and no two objects are equal except
if they are the same instance.
Here’s my workaround:

function empty(ar) {
    for(var k in ar) {
        return false;
    }
    return true;
}

Wrapper classes

The reason for this ‘gotcha’ is actually the same as the first.

js> var s = new String("abc")
js> var t = new String("abc")
js> s == t
false

My workaround for this is to always use:

var str = new String(some_val).toString();

instead of

var str = new String(some_val)

This translates to all wrapper classes.

For Boolean:

var bool = some_val==true

instead of

var bool = new Boolean(some_val)

For Number:

var num = new Number(some_val).valueOf()

instead of

var num = new Number(some_val)
Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.