Javascript Gotchas

While working on my last mobile app I ran into basic issues of javascript right before the final release. That caused additional delay in the release. These issues could have been avoided if I took care of them at the very beginning itself. I am going to discuss few of them here today. 

  • Date comparisons:
    You can compare two Date objects in javascript like this:

    var date1 = new Date();

    var date2 = new Date() - 2;

    date1.getTime() == date2.getTime();

    In my case I just wanted to compare the date and not the time. Simple solution to this problem was setting time for both the Date objects to midnight using setHour() and then comparing them. So I did something like this:

    date1.setHour(0, 0, 0).getTime() == date2.setHour(0, 0, 0).getTime();

    A feature of the app was failing randomly on debugging I found that it was because of the above line, which was little strange for me. I focused a little more and found the solution. I had missed setting milliseconds along with the hour, minute and second. So above line should have been like this:

    date1.setHour(0, 0, 0, 0).getTime() == date2.setHour(0, 0, 0, 0).getTime();

     

    So, when you are clearing time do not forget to consider milliseconds,
    specially if you are doing it for Date comparison.

     

 

  • Use try catch:
    I was making a lot of ajax calls which threw an exception if there was no Internet connection or some syntax error in the success/failure callbacks. Since I maintained a queue of ajax calls, none of the calls in the queue were going through after the exception. This made the app non-responsive.
    To solve this problem I added try catch block. This way whenever the exception occurred I could handle that inside catch block and save the app from breaking.

    try {
        $.ajax({
    
            type: requestMethod,
    
            dataType: "json"
            contentType: contentType,
    
            processData: processData,
    
            url: url,
    
            data: data,
    
            timeout: 20000
        })
    
        .done(successCallback)
    
        .fail(failCallback);
    
    } catch (error) {
    
    // Handle exception
    
    } finally {
    
    }

                 Exception at any point in javascript code can break your application.
                 So be prepared for it and emphasise on thinking about all possible exceptions
                 whenever writing a piece of code. 

 

  • Array referencing issue:
    When you intend to use one array object across different classes take proper precaution while manipulating the REFERENCE. For instance to clear contents of an array using different reference variable:
var ar1 = [2, 3, 4];
var ar2 = ar1;

ar2 = [];

console.log(ar1);

console.log(ar2);

This code will give following output:

[2, 3, 4]
[]

Because here we are not really manipulating ar1, rather we are re-assigning ar2 variable with a new array([]).
Right way to do this would be:

var ar1 = [2, 3, 4];
var ar2 = ar1;

ar2.splice(0, 3);

console.log(ar1);

console.log(ar2);

Which will now output:

[]
[]

These kind of issues cause hard to debug problems specially if your app is huge.

  • Event propagation and Event  bubbling:
    When you are handling any event like onclick, onkeyup etc, stop event propagation inside the handler if you do not want it to propagate further.
document.getElementById(‘name-input’).onclick = function(e) {
// Business logic

    e.stopPropagation();

    return false; // any one of them

};

You should do it explicitly otherwise, this is one of the bugs which can make app misbehave at points.

 

  • Be careful with equality comparison:
    When the operands of an operator are different types, one of them will be converted to an “equivalent” value of the other operand’s type this is called type coercion . For instance, if you do:
    boolean == integer
    The boolean operand will be converted to an integer: false becomes 0, true becomes 1. Then the two values are compared.
    However, if you use the non-converting(strict) comparison operator ===, no such conversion occurs. When the operands are of different types, this operator returns false, and only compares the values when they’re of the same type. I would recommend you to use === over == to avoid bugs.

  • Always use `var` to declare a variable
    Always use var. Variable declaration without `var` will traverse scopes all the way up till the global scope. It will declare it in the global scope if variable with that name is not found.

(function() {
    foo = 5;
    var bar = 10;
})();

console.log(foo); // outputs 5
//console.log(bar); // error: bar is not defined


A common mistake that most of us make is not using var in loops (e.g. for(i=0; i>10; i++) when i has not been previously declared) which might bear unexpected results.

 

Apart from above, you must insist on the best utilization of the debugger tools such as chrome debugger:

  1. Use breakpoints
  2. Apply watches
  3. Use console to run test scripts to clear concepts then and there
  4. Use network tab to inspect your request and response data.
About CauseCode: We are a technology company specializing in Healthtech related Web and Mobile application development. We collaborate with passionate companies looking to change health and wellness tech for good. If you are a startup, enterprise or generally interested in digital health, we would love to hear from you! Let's connect at bootstrap@causecode.com

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY UPDATED!

Do you want to get articles like these in your inbox?

Email *

Interested groups *
Healthtech
Business
Technical articles

Archives