Common JavaScript Mistakes

Dibuat pada - Perubahan terakhir pada

Before you start learning about Javascript mistakes, you must first master its ins and outs. Many developers say that if you want to learn JavaScript from books, you should start by reading "JavaScript: The Good Parts". It's a classic for JavaScript developers. The book is reasonably dated, but many of the best practices and guidelines presented there will be resolved by the new EcmaScript6 standard. You can read more about the new standard in my previous article.

Once you've learned all you can about Javascript, you can focus on the things you need to avoid. There are things in JavaScript that can easily trip up the unaware developer. Here are some of them.

One of the most common mistakes is the mixing of undefined and null values. Usually, developers who are new to JavaScript don't know the difference between these – specifically when one or the other should appear in the code, and how to defend against these. The null values only come into play for objects, while undefined can be methods, variables or properties. For example:

var myCar = {
   engine: "V8",
   horsePower: 440,
   year: 1998,
   manufacturer: null
};
// will throw an error, saying start() is not defined
myCar.start();

// will throw an error, saying weight is not defined
console.log(myCar.weight);

// will print null to the console
console.log(myCar.manufacturer);

Another common mistake is being unaware that JavaScript variables are not block level variables, as these are available on function level or globally. This language feature can have pros and cons. Here's an example:

var indexOf = function(item, array) {
   for (var i=0; i< array.length; ++i) {
       if(array[i] === item) {
           break;
       }
   }
   return i;
};

//the result will be 6
var myItemPosition = indexOf(123, [1, 2, 3, 4, 5, 88, 123, 45]);

Another common mistake involves the use of == for equality checking instead of ===. The difference between the two operators is that === does reference comparison, while == does value comparison. Check out this code:

//evaluates to true - this is what we would expect
123 == 123

//evaluates to true - this seems strange for developers coming from static typed languages
123 == "123"

//evaluates to true - this is what we would expect
123 === 123

//evaluates to false - because the types are different, although the values are the same
123 === "123"

It's recommended to always use the === operator for comparison. If you do it this way, you are more likely to avoid the execution of unwanted code blocks.

Every number in JavaScript is represented as a 64 bit float, and because of this, situations can arise when operations with decimal numbers don't have the expected result. Here's an example:

var apple = 0.1;
var pear = 0.2;

// total will have the value 0.30000000000000004
var total = apple + pear;

JavaScript isn't the only language that has issues with float values—other languages have these errors too. This is the reason why double (precision) types were introduced in languages like Java and C#.

Numbers can be added (using the + operator), but strings can also be concatenated using the same operator (+ operator), so be careful when using the adding and concatenating operators. For example:

// result will be equal to 156
var result = 123 + 33;

// result2 will be equal to "12333" - as string
var result2 = "123" + 33;

People coming from an OOP background are used to the this keyword. Well the this keyword is different in JavaScript. The value returned when you use it depends on how the function it's being used in is invoked.

var myHouse = {
   rooms: 1,
   bathrooms: 1,
   address: "Main av. 123",
   getAddress: function() {
       // this - will be the whole myHouse object
       return this.address;
   }
};

console.log(myHouse.getAddress());

Here's another use for it – storing data in constructor functions:

var Notebook = function(){
   this.processor = "x86";
   this.memory = "8GB";
   this.harddisk = "256GB";
   this.myToString = function () {
       return this.processor + " " + this.memory + " " + this.harddisk;
   }
};

var machine = new Notebook();
console.log(machine.myToString());

When working with strings many times, you need to replace some parts of it. The JavaScript string type has a replace method, but sometimes developers forget that this only replaces the first occurrence of the replaceable string.

var myString = "one, two, three, three, four";

// will display: one, two, , three, four
console.log(myString.replace("three", ""));

I could enumerate more usual mistakes, but these are the most common. Each of these can be avoided if you read and study the differences between JavaScript and the programming language(s) that you're familiar with. That way, you'll be more likely to pay attention to the differences as well as their similarities.

mempostingkan 23 Juli, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Artikel berikutnya

SydStart Speaker Spotlight: Diajeng Lestari