Skip to content

Coding standards in Javascript

This is more of a plea than a post, but I would like to impress upon you something important. When it comes to Javascript, please do not throw everything you know about good OO practice out the window!

Javascript has gained a bit of a reputation for being misused. It is almost understandable, as it is so easy to do things that you know you really shouldn’t. Oh look, a shortcut! Bad idea. When you come back to try and untangle this shortcut later, you end up with a patchwork of dependencies. The whole thing becomes a nightmare. Once you throw JQuery into the mix it gets even worse.

See the example below.

function User(FirstName, LastName)
     this.firstName = Firstname;
     this.lastName = LastName; = this.firstName + "." + this.LastName + "";
     this.username = this.firstName + "." + this.lastName;
     this.usernameChanges = 0;

     this.changeUsername = function(newUsername)
         this.username = newUsername;

Given this as a starting template, especially to someone who is just beginning to learn Javascript, they might be tempted to implement something like the below with the use of JQuery.

$('#changeUsername button').on('click', function(){
     currentUser.username = $('#newUsername').val()

This is the start of a slippery slope. Straight away they have already lost the count increment that could be crucial to another part of the program.

Stay vigilant and where standards have lapsed a bit, try to go back and refactor where possible. I find that refactoring is one of the best means to get to grips with the structures and best practices of a given language.

Published inJavascript

Comments are closed.