Extending Javascript's Array
If you had told me a year ago that I'd not only be using Javascript on a daily basis, but actually enjoying it, I would have laughed in your face before making a cynical comment.
However, it's quickly becoming my favorite language simply because of how malleable it is. For instance, I sat down today to implement some syntactic sugar for Arrays and in less than a few minutes had extended the base Array object.
(function(){
Array.prototype.first = function() {
return this[0];
};
Array.prototype.last = function() {
return this[this.length - 1];
};
Array.prototype.skip = function(num) {
return this.slice(num,this.length);
};
Array.prototype.take = function(num) {
return this.slice(0,num);
};
}).call(this);
Sure, it's 14 simple lines of code, but they're methods that make sense at a glance and call to mind my old days using Linq in the C# world. Now all I have to do is pull in this little library, and all my Arrays have .last(), .first(), .skip() and .take().
Written by James West
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside