Search code examples
javascriptobject-literal

What is this thing in JavaScript?


Consider:

var something = {

    wtf: null,
    omg: null
};

My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it?


Solution

  • It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties:

    var myobj = {
        name: 'SO',
        hello: function() {
            alert(this.name);
        }
    };
    

    And you can iterate through the properties using a for loop:

    for (i in myobj) {
        // myobj[i]
        // Using the brackets (myobj['name']) is the same as using a dot (myobj.name)
    }