No Comments

When I was first learning to code, something that came up a lot was to always comment your code. Code comments have value, but despite what my teachers at the time may have thought, you should actually try not to use comments.

This isn’t to say you shouldn’t communicate to the reader what the code is trying to do, you should just do that by writing readable code rather than relying on comments.

You do this through a variety of methods, some of which I’ve already covered in previous posts. Things like writing descriptive functions, not abbreviating your variable names, simplifying the code by keeping variables close to the functions that use them, and limiting arguments passed to functions and methods. Bascially this:

var scandal = {
  title: "Moon landing a hoax",
  peopleInvolved: [ "Niel Armstrong", "Buzz Aldrin" ],
  evidenceAvailable: [ "back-stage.mp4", "set-photo.jpg", "confession.pdf" ],
  mediaCoverage [ "www.crackpots.com", "www.flateathers.org" ],
  securityStatus: "TOP SECRECT"
}

function coverUpScandal( scandal ) {
  promotePerson( scandal.peopleInvolved[0] );
  destroy( scandal.evidenceAvailable );
  discredit( scandal.mediaCoverage );
  scandal.securityStatus = "Super duper ultra secret";
}

Is better than this:

//Create a scandal object
var scan = {
  // scandel title
  t: "Moon landing a hoax",
  // names of the people involed in the scandel
  pplIn: [ "Niel Armstrong", "Buzz Aldrin" ],
  // evidence avalible
  ea: [ "back-stage.mp4", "set-photo.jpg", "confession.pdf" ],
  // media outlets covering the scanal
  mc [ "www.crackpots.com", "www.flateathers.org" ],
  // security status of the scandal
  ss: "TOP SECRECT"
}

function cus( scan ) {
  // promote Niel Armstrong
  prmtPrsn( scan.pplIn[0] );
  // destory the scandel evidence
  des( scan.es ); 
  // discredit the media coverage
  dis( scan.mc );
  //change the security status of the scandal
  scan.ss = "Super duper ultra secret";
}

DRY variables

The concept of DRY code is simple, Don’t Repeat Yourself. So if you look at some code you’ve just written and notice it’s looking a bit moist, AKA the same stuff repeating over and over, there’s a good chance it’s an opportunity to refactor.

This is also true with variable declaration. Take the this example:

var umbrella = "open";
var raincoat = "on";
var gumboots = "on";
var music = "Singing in the rain";
var action = "Jumping in puddles like a man";
var danceMoves = "The Swim";

Notice how when declaring loads of variables we tend to repeat var a lot? Not very DRY now is it? Let’s put a towel over it:

var umbrella = "Closed",
raincoat = "off",
gumboots = "off",
music = "Walking on sunshine",
action = "slip, slop, slap",
danceMoves = "The twist";

Small difference’s like this add up over the course of a project so it’s best to make these your default habits when you’re a beginner.

Equals vs equals

In JavaScript not all comparisons are created equal… see what I did there. Let’s say we’re comparing two values like this:

if ( 42 == “42” ) {
 return “The meaning of life is 42”; 
}

The use of “==“ will compare two values regardless of their type, so in this example, it will return “The meaning of life is 42”. Used correctly this can be fine of course, but it can leave you open to issues like this:

var meaingOfLife = “41”;

if (meaningOfLife == 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

In this example, we’ve done the same comparison but then tried to add to the meaningOfLife variable which we can’t do because it’s a string, not a number. This is why as a general rule it’s best practice to use “===” for comparison as it will compare both value and type. Here’s an updated example:

var meaingOfLife = “41”;

if (meaningOfLife === 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

This version will correctly return “41” due to the fact the if statement will return false because the items match in value but not type. Do yourself a favour and default to “===“, it’s the comparison you’re likely to want the majority of the time.

Zombie code

Part of developing (and certainly learning to develop) is creating code, commenting it out, and creating a better version. As you get into a flow state with coding it’s really easy to get into he habit of doing this and not going back and clearing out the undead code comments.

Here’s an example of what I’m talking about.

function thriller() {
  return “Something evil\'s lurking from the dark”;
}

//function funkyTown() {
//  chargeKeytar();
//  dressInPastels();
//  return “Gotta make a move to a town that\'s right for me”;
//}
//funkyTown();

thriller();

The trouble with code like this is it’s not clear why the commented out code is there. Is the intention to reworking and use it? Can we remove this because the code was old? Was it commented out accidentally?

Zombie code is ambiguous code, and that’s not helpful for anyone. It’s fine in your own dev environment in the short term, but don’t leave it in too long and never let the zombie out in public. It will only eat everyone’s brains.

Keep your friends close and your variables closer

Back in the day, I used to have this habit of declaring all of my variables at the top of the file. My thinking at the time was it would keep everything organised so if I needed to jump to one I’d know where to go looking.

While that might sound like a sensible approach I’ve recently learnt there are quite a few shortcomings of doing this. The main one being the larger the project gets the more difficult it is to debug problems. Jumping about the file all the time just adds to the dreaded mental load, and that reduces your problem-solving skills.

Instead, try putting your variables close to where they’re used. It will reduce your variable hunting and in the rare situations you can’t find something, remember you can just use search.

How to function correctly

Coding is a fairly amazing thing to be able to do. There are effectively no limits to what can be done when you’re more or less writing the universe from scratch. Having said that if Spider-Man movies have taught us anything (and I think we can all agree they have) it’s that with great power comes great responsibility. So yes you can do anything, but the truth is your functions at least shouldn’t do everything. When you’re writing a new function make sure it’s only doing what its name implies. Take the following example:

function setHipsterEBikeSpeed( speed ) {
  brewHipsterCoffee( “Double shot decafe soy latte” );
  if ( speed < 20 ) {
    return “Low and slow”;
  { else if ( speed < 40 ) {
    return “Fast and furious”;
  } else {
    return “Might be safer to walk”;
  }
}

The name of the function implies we are going to use it to set the speed of a hipster e-bike, and while that is true it’s also brewing a hipster coffee at the same time, despite not making that clear in the name.

Ideally, the best approach here is to not brew coffee while setting the speed of a hipster ebike (this is true in life and code), as functions are best to be unitaskers the vast majority of the time. If for some reason your function needs to do a combination of two or more things then make sure it’s descriptive enough to communicate what it will do. Other developers will thank you for it.

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.

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.