JavaScript Objects

Here's an example of a JavaScript object:

var some_object = {  
    key: "value",
    another_key: "another value",
    the_answer: 42
}

If you say this looks like a hash in Ruby or a dictionary in Python, you're spot on. That's basically what it is.

Here's how you'd access the properties of this object:

console.log(some_object.key, some_object.another_key, some_object.the_answer)  

Running this will get you value another value 42.

If you simply wanted to loop through every key in an object you could use Object.keys:

var keys = Object.keys(some_object)  
for(var i = 0; i < keys.length; i++) {  
    console.log(keys[i], ':', some_object[keys[i]])
}

which would give you:

key : value  
another_key : another value  
the_answer : 42  

You can also give objects methods:

var player = {  
    name: 'player',
    att: 2,
    def: 2,
    hp: 10,
    attack: function (monster) {
        monster.hp -= Math.floor(Math.random()*this.att) - Math.floor(Math.random()*monster.def)
    }
}

var monster = {  
    name: 'monster',
    att: 2,
    def: 2,
    hp: 10,
    attack: function (player) {
        player.hp -= Math.floor(Math.random()*this.att) - Math.floor(Math.random()*player.def)
    }
}

BTW, if you think this code is too copy-pasty, you're right, we'll fix that in a future post.

BBTW, I know I said I'd be using arrow functions from now on, but the this keyword is different for arrow functions. I tend not to use this, or even create objects with methods, but I did want to show you how to do it.

And, because I couldn't help myself, here's a little "game" with our player and monster:

for(var i = 0; i < 10; i++) {  
    while (player.hp > 0 && monster.hp > 0) {
        player.attack(monster)
        monster.attack(player)
    }
    if(monster.hp > 0) {
        console.log('monster wins!')
    } else if(player.hp > 0) {
        console.log('player wins!')
    } else {
        console.log('both player and monster are losers!')
    }

    monster.hp = 10
    player.hp = 10
}

Looking for a software developer?