JavaScript: pitfalls, or what if you don’t have a HashMap

Today I encountered a strange bug. The user added keywords for narrowing search results. Keywords are added one by one. All was well until the user tried to add a keyword ‘constructor‘.

Guess what happened next? No, nothing crashed. But nothing happened either! The keyword wasn’t added to others, that’s all.

When I started debugging the code, I saw the following:

isKeywordValid: function (keyword) {
    if (!keyword || keyword.length == 0) {
        return false;
    }
    var values = {};
    // check existing keywords
    this.keywords.each(function (item) {
        values[item.keyword] = true;
    });
    return !values[keyword];
}

This is a usual case of using a JS object as a hash. Can you guess what’s wrong with this implementation? Sure! Every JS object has a constructor. It’s a function used to create an object. So,  values[keyword] will always return something, namely the function object. (BTW, for the same reason, user wouldn’t be able to use ‘toString’ as a keyword).

The easy fix:

    //... same validation check
    return !values.hasOwnProperty(keyword);

JavaScript is a very interesting language. 🙂

Advertisements

About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

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 )

Google+ photo

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

Connecting to %s