Utilizing JavaScript’s Native Methods

Hack Pacific
Altcademy
Published in
2 min readMar 12, 2016

When we first started out learning how to code, we had to learn how to do things manually. That’s great and all but as we progress, we should utilize the standard methods in JavaScript to abstract our code and hide some low level implementation details. This not only makes our code easier to read, but it also improves performance on some occasions. Let’s look at a simple example of summing numbers in an array.

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];// The good old for loop
var forLoopSum = function(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(forLoopSum(numbers));
// -> 55
// Using Array.prototype.reduce
var sum = numbers.reduce(function(a, b) {
return a + b;
});
console.log(sum);
// -> 55

Well, that seems cleaner, doesn’t it? No more for loops. Technically, all of that low level details are tucked away in reduce. Let’s look at one more example. This time, we have an array of NBA players and we want to filter out those who have an average point per game of 15 or higher.

var players = [
{ name: "Kobe Bryant",
team: "Los Angeles Lakers",
ppg: 10.8,
mpg: 21.2
},{
name: "Kevin Durant",
team: "Oklahoma City Thunder",
ppg: 21.2,
mpg: 35.2
},{
name: "Stephen Curry",
team: "Golden State Warriors",
ppg: 25.2,
mpg: 36.9
},{
name: "Tim Duncan",
team: "San Antonio Spurs",
ppg: 12.3,
mpg: 28.7
}
];
// The way of the for loop
var playersHigherThan15Ppg = [];
for (var i = 0; i < players.length; i++) {
if (players[i].ppg >= 15) {
playersHigherThan15Ppg.push(players[i]);
}
}
console.log(playersHigherThan15Ppg);
// Using Array.prototype.filter
var filteredPlayers = players.filter(function(player) {
return player.ppg >= 15;
});
console.log(filteredPlayers);

Using filter method is a much cleaner way to accomplish this. As for performance, for loops do generally out perform reduce and map when dealing with long arrays of numbers.

However, when executing more complicated programs, native methods can outperform basic for loops significantly. This is because native methods are running native code; whereas, for loops are replicating the same logic in JavaScript.

A nice test snippet created by Anton demonstrates this perfectly. You can also check out his article Eloquent JavaScript with Underscore.js;

Altcademy.com offers affordable 100% online programs that teaches Full-stack Web Development.

--

--

Hack Pacific
Altcademy

Learn to create websites and applications in 10 weeks. Join our online programming courses with live Q&A, peer reviews and coached office hours.