Why do we write JavaScript like this?

Anders - Aug 21 '20 - - Dev Community

Before we start, I do realize that this may potentially come off as a little harsh or negative, but that is not my intent, I am just curious as to why we’ve ended up writing code this way? All the samples in this article are from this article: https://dev.to/papabearcodes/four-common-javascript-interview-coding-problems-1gdk.

Over the past several years I’ve been reading a lot of articles here on Dev.to and I just keep coming across JavaScript that looks like this:

const isPalindrome = string => {
  let revString = [...string].reverse().join('')

  const palindromeCheck = () => string === revString ?  true : false

  return palindromeCheck()
}

And I can’t help but wonder, why do people prefer writing code like this. It makes use of a lot of built in functions, lambdas and what not, but it's also perhaps a little more difficult to read than you’d like, and if you think about what it's actually doing, it's not very efficient.

Let’s break this one down:

We use the spread [...string] function to make the string into an array of characters (memory allocation), we then reverse that array (hopefully this at least is done in place by the compiler, but I doubt it), lastly we join that back up into a new string (memory allocation).

Second we declare a sub function that basically just performs a single comparison, this literally seems to have absolutely no purpose whatsoever.

I’d personally write the thing something like this:

function isPalindrome(s) {

  for (var i = 0; i < s.length / 2; ++i) {

    if (s[i] != s[s.length - 1 - i]) {

      return false;
    }
  }

  return true;
}

Certainly a few more lines, and very “old looking” perhaps, but I am old ; ). Thing is though, this runs faster (albeit slightly), and in my mind at least is also easier to read and understand. But maybe I’m just crazy.

This example also sticks out, from the same article:

const sum = (...args) => [...args].reduce((acc, num) => acc + num, 0)

Granted, it is actually preceded by a more readable alternative first, that again avoids the things that I just think you should always avoid, poor readability.

function sum() {
  let total = 0

  for (let num of arguments) {
    total += num
  }
  return total
}

There is no way you’d ask yourself how that works.

However that example uses the “of” operator on the arguments array, a “new” fun feature. Sadly, performance is affected, using jsbench.me to compare the two the one line version is massively faster, the second version is reported as 92% slower than the first. This probably doesn’t matter for a function that runs once or twice but if we keep following this kind of pattern of blatant disregard for performance we will get into a lot of trouble eventually (Some may even say we are already, I may be one of those people ; ).

I did my own take as well, old school javascript again:

function sum() {

  var sum = 0;

  for (var i = 0; i < arguments.length; ++i) {        

    sum += arguments[i];
  }

  return sum;
}

Super simple, also as it turns out, super fast, our old one line champ is reported as being 74% slower than this above function.

Rounding up, let’s take a third function:

const captilizeAllWords = sentence => {
  if (typeof sentence !== "string") return sentence

  return sentence.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

Split, Map, Slice, Join.. so many array operations in action here. Let’s try a more basic approach:

function captilizeAllWords(s) {

  var capitalize = true;
  var returnValue = '';

  for (var i = 0; i < s.length; ++i) {

    var c = s[i];

    if (c == ' ') { 

      capitalize = true; 

    } else if (capitalize) {

      c = c.toUpperCase();
      capitalize = false;
    }

    returnValue += c;
  }

  return returnValue;
}

This is a much more explicit take. Again it’s slightly longer. And again it's faster. JSBench reports the first variant as 33% slower here. An additional benefit of this solution, if you actually wanted to do this for things after a tab or new line, that doesn’t really take much thinking of code to achieve.

That does it for this old developer ranting about new stuff style article, hopefully this can lead to some healthy discussion if nothing else =).

Eat your vegetables, make your code readable, and don't forget to BENCHMARK!

. . . . .
Terabox Video Player