Write JavaScript properly, please

I am also (sometimes) guilty of writing terrible JavaScript code - it's a language that is very easy to learn and use but to use it in a good and concise manner, now that's difficult. Over the past few months I have spent a lot of time learning JavaScript, the dos and don'ts, bst practices, common errors and so on. There are a lot of articles out there describing these common sense topics and I thought I'd jump on board and write yet another one - but this post is going to look at the mistakes I have done - and as I have quite a lot of followers reading this blog who have many times said that they are new to JavaScript, I would like them to avoid the mistakes that I have done (or in fact still make).

This post is a call to start writing JavaScript properly!

Okay, one of the biggest issues that I have: writing code in a lazy way. You all know what I mean. It's the things from "why should I write extra opening and closing curly braces" to "why would I use the var keyword?"

Let's go through some of these common mistakes that made my life difficult before. I have had some good conversations with people over the past week about coffeescript and Jade - two technologies that I'd like to use but for whatever reason I can't get used to them - it's this tabbing layout that I can't get my head around - I feel that it confuses me as opposed to helping me. This confusion is also valid when sometimes I omit curly braces from my JavaScript code - consider the following:

function test() {
  console.log("call me maybe");

if (a===0)
  console.log("super-true statement");
  test(); //epic fail
  console.log("i am so false");

This will simply cause a SyntaxError in your code - quite rightously. As a general rule of thumb - always make sure you use the curly braces.

The next thing I'm guilty of is missing the var keyword. Here's an interesting example for you:

function fun() {
  var a = "me"
      b = "you",
      c = "them";
var b = "new you";
ReferenceError: a is not defined //huh?

//returns 'you' (huh?!)

//returns 'them' (I give up!)

Is this confusing enough? You see here the problem is that I am trying to chain the variable creation inside my fun() function but I have missed a comman between variables a and b. This means that now variable b is in fact a global variable. You don't believe me? Check this out:

["top", "window", "location", ..., "fun", "b", "c", ] //wow!

There are a lot of other gotchas when it comes to JavaScript and in the future I may post some articles about these but at the moment these two "mistakes" are the ones that have caused me the most issues unfortunately.

Show Comments