JavaScript

Use the triple equal for conditions to avoid type coercion

JavaScript comparison symbol does not work in the same fashion as other languages. The double equal symbol == performs something called type coercion before doing the comparison. What it means is, it forces two values down to a common value. For example, with type coercion, an empty string and the value 0 are brought down to the same value, which is false.

"" == 0
"" == false
 0 == false

All those evaluate to true. When properly used, this could be a powerful feature of JavaScript; because it allows you to compare values that are only loosely related. Unfortunately, this creates a foreign concept to most people coming from a more strictly typed language. To make things easier to maintain, it is better to avoid type coercion all together.

You never want to compare an empty string to 0. Maybe you want to compare its length to it. Here is one place that was once a source of headache for me. I tried to check if an class is present in a string and had a hard time figuring out what the problem is.

<div class="selected myclass random">
<!-- Html -->
</div>

// JS
var allElements = document.getElementsByTagName("div"),
    className = "selected",
    filteredElements = [],
    currentElement,
    currentClass,
    index;

for (var i = 0,l= allElements.length; i < l; i++){
    currentElement = allElements[i];
    currentClass = currentElement.className;
    index = currentClass.indexOf(className);
    if (index) {
        filteredElements.push(currentElement);
    }
}

The index variable saves the current position of the string you are looking for. Unfortunately, I did not know that the .indexOf() method returns -1 when the string is not found. My string was found, but it was at character number 0. Remember that with type coercion, 0 equals false. So my filteredElements array was always empty. Even (index === 0) would have worked.

By using the triple equal sign === you have the assurance that both the value you are comparing have the same data type.

"1" === 1 // false

This will evaluate to false because the first value is a string and the second is a number. The only time you would want to omit the comparison symbol, is when you are expecting a true or false.

Instead of:

var isChecked = true;
if (isChecked === true){
    // code
}

You could write:

var isChecked = true;
if (isChecked){
    // code
}

Try to replace all the == to === in your code, you will be surprised by all the bugs you may encounter in your code.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only