adgrinders
adgrinders

Reputation: 21

JavaScript Weird behavior in a condition

there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code

function fibonacci () {
    let fibonacciNumber = document.getElementById("my-input").value;

    let numberInitialize = 0; 
    let numberNext = 1; 
    let sum = numberInitialize + numberNext;

    if (fibonacciNumber === "" || fibonacciNumber === 0) {
        return (0);
    }


    for (index = 1; index < fibonacciNumber; index++) 
    {
        numberInitialize = numberNext;

        numberNext = sum;

        sum = numberInitialize + numberNext;
        console.log(sum);
        console.log("premier tour");
    }
    console.log(sum);
    document.getElementById("fibo-result").innerHTML = `${sum}`;
}

So on the html side I just have an input and im writing down number, my questions concerned this line of code

if (fibonacciNumber === "" || fibonacciNumber === 0) {
    return (0);
}

when im writing down 0, its still printing one but i write the condition like that

if (fibonacciNumber === "" || fibonacciNumber <= 0) {
    return (0);
}

its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?

Thanks guys

Upvotes: 1

Views: 295

Answers (2)

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

You will need to use parseInt() and then treat the input as integer.

let fibonacciNumber = parseInt(document.getElementById("my-input").value);

Upvotes: 1

Nick
Nick

Reputation: 16576

The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.

Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.

You can see this all in action below.

console.log("0" === 0);

console.log("0" <= 0);

Upvotes: 1

Related Questions