Skip to main content

Posts

Showing posts from August, 2018

JavaScript: array.every()

I decided to relearn JavaScript after not having worked with it since school so I'm going through the JavaScript track at exercism.io. Yesterday, I ran into behavior I didn't expect with Array.prototype.every(), and after getting help from some actual JS developers, they were surprised too.

The Exercism project I was working on was to create a class to check if a sentence is a pangram. (A pangram is a sentence that contains every letter of the alphabet.)

My approach was simple: create a sparse array with 26 elements (one for each letter) walk the sentence, and for each letter, look up its index in the alphabet, then set that index in my array to true. After I was done walking the sentence, I then used Array.prototype.every() to check the results. Array.prototype.every() seemed perfect for this: it takes a callback function, and applies it to every element of an array. If it gets back a falsy return value from one an element, it stops processing and returns false. If it makes i…