1

I am trying to write a Java Script program that should have two variables. You should add and display the sum only if they are numbers. If they are of any other type you should show a message "Sorry.... Only Nos will be added" Please have look in the below snippet. Thanks in advance

<script>
var x = Number(prompt("Enter First Choice"));
var y = Number(prompt("Enter Second Choice"));
var x1 = typeof x;
var y1 = typeof y;

if(x1==='number' && y1==='number'){
document.write(x+y);
}
else{
document.write("Sorry.... Only Nos will be added");
}
</script>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Souradip
  • 111
  • 1
  • 10

1 Answers1

0

Because typeof NaN is number. And NaN === NaN is false you should use isNaN.

var x = Number(prompt("Enter First Choice"));
var y = Number(prompt("Enter Second Choice"));

if(!isNaN(x1) && !isNaN(y1)){
  document.write(x+y);
}
else{
  document.write("Sorry.... Only Nos will be added");
}

I short code will be like.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73