0

Function in JS

    function punch(){
    var a,b,result;
    a=document.getElementById('n1').value;
    b=document.getElementById('n2').value;

    var x=parseInt(a);
    var y=parseInt(b);
    result=x+y;


     if (result===NaN)
     result =0;

I know this condtition is false and it gives output of x+y. On empty fields it always return NaN value when change it to

if (result!==NaN)
 result=0;

Now it becomes true but it gives x+y also 0.

document.getElementById('n3').value=result;   
}

HTML Code

<input type="text" id="n1" placeholder="Value 1"/>
<input type="text" id="n2" placeholder="Value 2"/>
<button type="button" onClick="punch()">Click For Answer</button>
<input type="text" id="n3" placeholder="Answer"/>
0

1 Answer 1

1

Nothing, including NaN, is ever === to NaN. In fact one way to test for NaN is to exploit that!

if (result !== result)
  result = 0; // must have been NaN!

You can also use isNaN():

if (isNaN(result))
  result = 0;
Sign up to request clarification or add additional context in comments.

2 Comments

@DontVoteMeDown yes I would use that preferentially; the first is just for illustration (though I've seen it used).
Pointy Thanks for help! just play little bit with variable (result !== result) and its become true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.