loading...

One life saving Javascript Tip

kepta profile image Kushan Joshi Updated on ・1 min read

Always Exit Early !

function mostComplicatedFunction(data) {



    if (!data) {
      return; // << Always exit early whenever you can!
    }



    // Bang Bang!

    var {words, ii, position, word, current, sentence} = data;

    /**
     * @default 100
     */
    num_words = num_words || 100;

    words = [LoremIpsum.WORDS[0], LoremIpsum.WORDS[1]];
    num_words -= 2;

    for (ii = 0; ii < num_words; ii++) {
    position = Math.floor(Math.random() * LoremIpsum.WORDS.length);
    word = LoremIpsum.WORDS[position];

    if (ii > 0 && words[ii - 1] === word) {
        ii -= 1;
    } else {
        words[ii] = word;
    }
    }

    sentences = [];
    current = 0;

    while (num_words > 0) {
    sentence_length = this.getRandomSentenceLength();

    if (num_words - sentence_length < 4) {
        sentence_length = num_words;
    }

    num_words -= sentence_length;

    sentence = [];

    for (ii = current; ii < current + sentence_length; ii++) {
        sentence.push(words[ii]);
    }

    sentence = this.punctuate(sentence);
    current += sentence_length;
    sentences.push(sentence.join(" "));
    }

    return sentences.join(" ");

}

Discussion

pic
Editor guide
Collapse
kepta profile image
Kushan Joshi Author

This early exit post was inspired by the countless number of functions I have seen which do something inside knees deep { { { brackets.

// Comparison
function early(data) {
  if (!data) {
    return data;
  }

  return data.map(r =>
    r
      .split(',')
      .join('-')
      .slice(1)
  );
}
function late(data) {
  if (data) {
    return data.map(r =>
      r
        .split(',')
        .join('-')
        .slice(1)
    );
  } else {
    return data;
  }
}

Collapse
rhymes profile image
rhymes

Not sure what's the tip eheh :D

Collapse
kepta profile image
Collapse
jjjjcccjjf profile image
endan

I think OP means that you should handle the checking of arguments before any other code to prevent side-effects.

Collapse
lmbarr profile image
Luis Miguel

I have seen this pattern so many times in senior dev code....