Categories
Geekpulp

Simplify conditional statements

Consider the following code:

function danceLikeNoOnesWatching( person ) {
  if ( person.danceMoves === “amazing” ) {
    return false;
  } else {
    return true;
  }
}

Looks good right? It’s logical and easy to understand, just your standard if statement. All true, but over the course of an entire project you’ll make a lot of considtional statements like this and using 5 lines of code when 1 will do can create some serious size increases to your code. To reduce the codes size, just return the output of the conditional like this:

function danceLikeNoOnesWatching( person ) {
  return person.danceMoves === “amazing”;
}

Simpler, still easy to understand and now light weight.

Categories
Geekpulp

Avoid abbreviating variables

Do you know what’s super annoying when reading someone else code? Abbreviated variable or function names. Until late 2017 I hadn’t done any coding in years so I was rusty as all hell, and truthfully I still am. One thing I noticed when looking at other peoples code was how it made it far slower to read and learn from when all the variables and function names are abbreviated. Yes, it might be faster for the person writing the code at the time, but anyone else exposed to that code carries a bit more mental load to decipher it. Take this simple code for example:

var prsn = {
  n: "Emma",
  a: 7,
  loc: "Palmerston North",
  frnds: [ "Ella", "Megan", "Tom" ]
};

prsn.prntFrnds = function() {
  this.frnds.forEach( function( frnd ) {
    console.log( frnd );
} );
}

Now compare this to the same function without abbreviated variables and function names:

var person = {
  name: "Emma",
  age: 7,
  location: "Palmerston North",
  friends: [ "Ella", "Megan", "Tom" ]
};

person.printFriends = function() {
  this.friends.forEach( function( friend ) {
    console.log( friend );
} );
}

Both examples are technically the same. However, it’s far easier to understand the second example at a glance, especially for a beginner who’s already looking at something relatively unfamiliar.

So the next time you catch yourself writing a block of code just remember to take a second for the next person reading it. Your code should be as descriptive as possible, so even a junior developer understand what it’s for at a glance… or someone who hasn’t seen the code in a long while… chances are that someone will be you at some point.