randomElement

I’ll be honest, I’m sympathetic to the view that exending Object.prototype is bad practice. But I’ll be damned if it isn’t conveinent.

//This little snippet does the bad practice of overloading default JavaScript objects. I know it's bad taste, sue me.
//It only works on arrays.
//['a', 'b', 'c'].randomElement()
Object.prototype.randomElement = function(){
var randomIndex = Math.floor(Math.random() * this.length);
return randomString = this[randomIndex];
}

PROGRAMMING
programming javascript snippet gist