Search code examples
javascriptnumbers

How do I check if a variable is an imaginary number inside JavaScript?


I am making a calculator, and I don't want NaN to show up for results of imaginary/complex numbers, and instead just an error message. How would I check this inside of JavaScript?

I looked around on the web but couldn't find a definitive answer.


Solution

  • You can use isNaN().

    let x;
    
    const rand = Math.round(Math.random());
    
    if (rand) x = 5 + 1;
    else x = 5 + "a";
    
    if (isNaN(x)) console.log("error");
    else console.log(x);