1

I have a some code where If I type in a string, it should return false, yet it returns true, then runs the piece of code its not supposed to run.

var f1
var f2
var d
var nth
var answer

function start() {
  f1 = prompt("First Term")
  f1 = parseInt(f1)
  f2 = prompt("Second Term")
  f2 = parseInt(f2)
  d = f2 - f1
  nth = prompt("Nth Term")
  nth = parseInt(nth)
  if (f1 != NaN || f2 != NaN || nth != NaN) {
    answer = f1 + d * (nth - 1)
    alert("Terms:\n1st Term: " + f1 + "\nSecond Term: " + f2 + "\nNth Term: " + nth + "\n\nCalculating Common Difference:\n d = " + f2 + " - " + f1 + ", or d = " + d + "\n\nUsing the explicit formula:\n" + f1 + " + " + d + "(" + nth + " - 1) = " + answer)
  } else {
    alert("Please type in numbers.")
  }
}

start();

Anyone know why its running the code, even after putting in a string?

Peter B
  • 22,460
  • 5
  • 32
  • 69

1 Answers1

0

You can not compare NaN directly.

NaN !== NaN

Better use isNaN instead with negation (logical NOT !) and logical AND &&.

var f1
var f2
var d
var nth
var answer

function start() {
  f1 = prompt("First Term")
  f1 = parseInt(f1)
  f2 = prompt("Second Term")
  f2 = parseInt(f2)
  d = f2 - f1
  nth = prompt("Nth Term")
  nth = parseInt(nth)
  if (!isNaN(f1) && !isNaN(f2) && !isNaN(nth)) {
    answer = f1 + d * (nth - 1)
    alert("Terms:\n1st Term: " + f1 + "\nSecond Term: " + f2 + "\nNth Term: " + nth + "\n\nCalculating Common Difference:\n d = " + f2 + " - " + f1 + ", or d = " + d + "\n\nUsing the explicit formula:\n" + f1 + " + " + d + "(" + nth + " - 1) = " + answer)
  } else {
    alert("Please type in numbers.")
  }
}

start()
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392