Search code examples
javascriptif-statementdom

If statement isn't showing console.log when condition passed and continue work as unexpected


So there's a simple code with vanilla JavaScript.

const button = document.getElementById('btn');
const input = document.getElementById('amount');

let list = [];

button.addEventListener('click', () => {

    let num = +input.value;

    if (typeof num === 'number') {
        list.push(num);
        console.log(list);
    }

    else {
         console.log('Error. Try again and type in a number');
    }
})

Why the console.log statement isn't showing up in the console but instead it pushes NaN value to the list?

I tried to use else if instead of just else and passed the following condition: typeof num !== 'number'


Solution

  • The comments have basically already answered it, but I'll try my best to sum it up and explain it to you.

    In JavaScript, the plus operator before a string, let num = +input.value; in your case, will always convert the given string into a number, even if it isn't valid. To handle this, JavaScript has NaN, which stands for Not a Number, which funnily enough, is a number. So to actually check whether your input is a number, you have to use the isNaN function:

    const button = document.getElementById('btn');
    const input = document.getElementById('amount');
    
    let list = [];
    
    button.addEventListener('click', () => {
    
        let num = +input.value;
    
        if (!isNaN(num)) {
            list.push(num);
            console.log(list);
        } else {
             console.log('Error. Try again and type in a number');
        }
    })