Tib51
Tib51

Reputation: 162

Variables comparison

I have this simple problem with Javascript where I want to compare two variables, but somehow it doesn't work correctly. I even checked that the types of variables are the same. Please help. Specifically, I get alerts for numbers, and I even get the alert for current counter is 5 total is 5, although I would expect it to enter the "then".

function fun(idCount, finalCallback) {
this.idCount = parseInt(idCount);
var counter = 0;
var strings = {};
this.register = function(str, id) {
    counter++;
    strings[parseInt(id)] = str;

    if(counter == this.idCount) {
        alert("Going to override");
        //blabla
    } else {
        alert("Current counter is: " + counter + " Total " + idCount + ". Types: " + typeof counter + " and " + typeof idCount);
    }
}
}

Upvotes: 0

Views: 57

Answers (2)

htatche
htatche

Reputation: 693

Just to point that if you use == it doesn't matter if both objects are same type or not.

Example:

"0" == 0 // true

To force type comparison as well use ===

0 === 0 // true

Upvotes: 0

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

Try this,

function fun(idCount, finalCallback) {
    var self = this;
    this.idCount = parseInt(idCount, 10);
    var counter = 0;
    var strings = {};
    this.register = function(str, id) {
        counter++;
        strings[parseInt(id, 10)] = str;

        if(counter == self.idCount) {
            alert("Going to override");
            //blabla
        } else {
            alert("Current counter is: " + counter + " Total " + idCount + ". Types: " + typeof counter + " and " + typeof idCount);
        }
    }
}

Upvotes: 2

Related Questions