Bobbie Lincoln
Bobbie Lincoln

Reputation: 33

Why is 10 less than 9?

I have a function switcher() which has an Object argument, video. It should log 'Start' if video.start <= video.ende. It's working fine in most cases (example: video.start = 1 and video.ende = 3), but when video.start = 9 and video.ende = 10 it logs 'End'.

function switcher(video)   
{
    console.log("Start: " + video.start);
    console.log("End: " + video.ende);

    if(video.start <= video.ende) // Not working correctly
    {
        console.log("Start");
    }
    else
    {
        console.log("End");
    }
}

console.log() successes:

console.log: addon: Start: 1
console.log: addon: End: 3
console.log: addon: Start

console.log() Failed:

console.log: addon: Start: 9
console.log: addon: End: 10
console.log: addon: End

Why is it so?
How can I fix this?

Upvotes: 2

Views: 894

Answers (1)

Barmar
Barmar

Reputation: 780663

It sounds like video.start and video.ende are strings, not numbers, so they're being compared lexicographically, not numerically. Convert them to numbers before comparing.

if (Number(video.start) <= Number(video.ende))

Or you can fix the code that creates the video object so it converts to a number at that time.

Upvotes: 3

Related Questions