-2

So I have this code:

function step3() {
    //finds both answers
    answer1 = top1 / (2*a);
    answer2 = top2 / (2*a);
    console.log(answer1 + " " + answer2);
    solutions = isNaN(answer1)
    console.log(solutions)
    if (solutions = true) {
        console.log("no real sol")}
    step4()
}

and when I run that if answer1 is NaN it does print true, but every time it prints no real sol. Why does it do this? I thought it would only if solutions is true.

  • 2
    You don't need to check a Boolean explicitly for `true` or `false`. `if(solutions)` is all you need. – Scott Marcus Jan 15 '21 at 21:08
  • 2
    `if (solutions = true)` isn't checking if `solutions` is equal to true, it is _**setting**_ `solutions` equal to `true`. You want `if (solutions === true)` (or `==` depending on what type of equality check you want. – Alexander Nied Jan 15 '21 at 21:09
  • 1
    In addition to @ScottMarcus's comment, you're also using an assign operator (`=`) instead of an equality operator (`==`). – Ouroborus Jan 15 '21 at 21:09
  • 3
    Learn the difference between `=` , `==` and `===` – Roko C. Buljan Jan 15 '21 at 21:09

4 Answers4

1

You are using the assignment operator = instead of the comparison operators == and ===, so what solutions = true does is cause solutions to become true regardless of what it was on the prior line.

And, to check a Boolean variable, you don't need to compare it to true because an if statement will always be looking for the "true-ness" of the condition you pass, so your code should be:

function step3() {
    //finds both answers
    answer1 = top1 / (2*a);
    answer2 = top2 / (2*a);
    console.log(answer1 + " " + answer2);
    solutions = isNaN(answer1)
    console.log(solutions)
    if (solutions) {
        console.log("no real sol");
    }
    step4()
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

In JS the comparison operator for checking whether two values are equal is == but you only have one = which sets the value to true, simply use

if(isNan(answer1)) { /*your code*/ }

To avoid any confusion

Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
0

I don't know all of your code but you have just one equal sign between solution and true. In comparisons we should use "==" not "="

function step3() {
    //finds both answers
    answer1 = top1 / (2*a);
    answer2 = top2 / (2*a);
    console.log(answer1 + " " + answer2);
    solutions = isNaN(answer1)
    console.log(solutions)
    if (solutions == true) {
        console.log("no real sol")}
    step4()
}
0

You have three options.

  1. if (solutions)
  2. if (solutions === true)
  3. if (solutions == true)

This previous questions has a lot information regarding the three possibilities... boolean in an if statement

Rob Breidecker
  • 604
  • 1
  • 7
  • 12