0

I have made my function that takes user input and outputs it as true if it is the same number and false if it isn't. Now my application always outputs it as false. Sorry if this is bad code, I am a noob.

I have tried to replace "== NaN" with "< 0" with no success.

function compare(a, b) {
  if (a == b) {
    var valid = true;
  } else {
    var valid = false;
  }
  return valid;
}

function test(first, second) {
  if (!isNaN(first) && !isNaN(second)) {
    alert(compare(first, second));
  } else {
    alert('TRY AGAIN');
  }
}


var firstStr = prompt('Enter first Number:');
var first = new Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = new Number(secondStr);

test(first, second);

I have not got any error messages however I got it stuck always on false, if there is anything else bad with my code please let me know.

2

3 Answers 3

0

You are using new Number() which will result in {} thats why it is always false

function compare(a, b) {
console.log(a,b)
    if (a == b) {
        var valid = true;
    } else {
        var valid = false;
    }
    return valid;
}

function test(first, second) {
    if(!isNaN(first) && !isNaN(second)){
        alert(compare(first, second));
    } else {
        alert('TRY AGAIN');
    }
}


var firstStr = prompt('Enter first Number:');
var first = Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = Number(secondStr);

test(first, second);

Sign up to request clarification or add additional context in comments.

Comments

0

When you use new Number(firstStr) you're creating an object that holds more than just its value.

If you want to have just the plain integer, remove the word new and it will return only its value.

If you plan on keep the new, you need to check for a.valueOf()and b.valueOf() on your compare function.

Comments

0

Just remove new Number()

// same code ...

var firstStr = prompt('Enter first Number:');
var first = firstStr; // remove new Number()

var secondStr = prompt('Enter second Number:');
var second = secondStr; // remove new Number()

test(first, second);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.