2

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?

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • Possible duplicate of [Javascript string/integer comparisons](http://stackoverflow.com/questions/5630123/javascript-string-integer-comparisons) – Makyen Oct 26 '16 at 23:24
  • Additional duplicate targets: [Why does “10” > “9” = false?](http://stackoverflow.com/questions/24025586/why-does-10-9-false) and [Why is one string greater than the other when comparing strings in JavaScript?](http://stackoverflow.com/questions/7087811/why-is-one-string-greater-than-the-other-when-comparing-strings-in-javascript) – Makyen Oct 26 '16 at 23:31

1 Answers1

3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612