Ruth Young
Ruth Young

Reputation: 888

Not entering loop even though it should

I am having loop issues in javascript.
I've come across a strange issue all of a sudden where for certain values my loop doesn't trigger, even though it seems it should.

var j = holiday_starts;

console.log(j);
console.log(holiday_ends);

if (j<=holiday_ends){
    console.log("TRUE");
}

Where in this case, holiday_starts is 6 and holiday_ends is 10 (checked with the console log). This is NOT logging TRUE. It only happens for some cases not others.

If I set the variables directly (j = 6, holiday_ends = 10) then it will log TRUE.

What have I missed? Is this due to something else in my code somewhere?

Upvotes: 0

Views: 69

Answers (4)

behkod
behkod

Reputation: 2777

They are being compared alphabetically because its assumed they are String.

Convert them explicitly to Number using Number() or parsInt(). Then you'll get right answer

Upvotes: 1

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

It is likely that one of the variables holds a string value.

Check this via typeof keyword:

var j = holiday_starts;

console.log(j);
console.log(holiday_ends);

if (j<=holiday_ends){
    console.log("TRUE");
}
else {
    console.log("Type of j:" + (typeof j) + " // Type of holiday_ends:" + (typeof holiday_ends));
}

And fix accordingly

Upvotes: 0

AVAVT
AVAVT

Reputation: 7133

I suspect you are getting holiday_starts and holiday_ends as string (probably from an user input?). When that happen, the comparition is made as string, and 6 is after 1 in the alphabet, "6" < "10" is false, like in this snippet:

var holiday_starts = "6";
var holiday_ends = "10";
var j = holiday_starts;

console.log(j);
console.log(holiday_ends);

if (j<=holiday_ends){
    console.log("TRUE");
}

In that case, you should parseInt the input before comparing, the below snippet works as intended:

var holiday_starts = parseInt("6");
var holiday_ends = parseInt("10");
var j = holiday_starts;

console.log(j);
console.log(holiday_ends);

if (j <= holiday_ends) {
  console.log("TRUE");
}

Upvotes: 1

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

You are comparing strings not integers. So just convert to integer types before comparing.

Like this:

if (Number(j)<=Number(holiday_ends)){
    console.log("TRUE");
}

Upvotes: 1

Related Questions