How an ES6 Codewars Kata Made Me Look Foolish

DZone 's Guide to

How an ES6 Codewars Kata Made Me Look Foolish

There are lots of sites offering competitive programming—a fun way to spend your spare hours. Some of the challenges can be quite tricky, and you might catch yourself stuck on a problem that seems simple. Let me share with you my experience...

· Web Dev Zone ·
Free Resource

First of all, let me introduce you guys to a fun way to spend your spare hours. It's called competitive programming, and these platforms offer you a way to have fun with the community and practice your programming skills!

There are lots of sites offering this, but I usually use only these two: topcoder.com and codewars.com. Codewars it is my favorite; they make references to karate and so call their challenges "katas." The users start at level 8 and advance until reaching level 1... the katas are also divided by levels, but you can try any level kata in any language.

So anyway, recently I started one kata that asked me to make a function that extends JavaScript's Array functionality called sum—that function should add all elements in the array and return the sum (a pretty intuitive name). I chose an "easy" kata because I was showing the website to a friend and finished it in about 1~2 minutes... or, so I thought. I ended up getting stuck on the problem for longer because my algorithm didn't work. I had written:

Array.prototype.sum = ()=>this.reduce((a, b) => a + b, 0);

But, it simply did not work! So, I searched and searched when I discovered that the reason the function did not work was because arrow functions ( '=>' operator without using function keyword) do not get their own "this" context. Instead, they inherit from the calling context (in this case, it was the global context). Arrow functions are elegant but are mostly used for callbacks because of this restriction. So instead, I tried:

Array.prototype.sum = function() {
  return this.reduce((a, b) => a + b, 0);

And finally, it worked.

Moral of the story: read ES6 updates, and never ever underestimate a Kata. They all have their fair value.

See my Codewars profile and follow me if you want to form an alliance!

That's all. Thanks! 

challenges, development, ecmascript 6, javascript

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}