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.

Jaydeep Galani
  • 4,842
  • 3
  • 27
  • 47
  • 1
    Remove the `new` keyword. It creates a `Number` object. – adiga May 31 '19 at 12:03
  • 2
    Possible duplicate of [Comparing equality of two numbers using JavaScript Number() function](https://stackoverflow.com/questions/36077773/comparing-equality-of-two-numbers-using-javascript-number-function) and [new Number() vs Number()](https://stackoverflow.com/questions/4719320) and [What is the difference between “new Number(…)” and “Number(…)” in JavaScript?](https://stackoverflow.com/questions/2381399) – adiga May 31 '19 at 12:04

3 Answers3

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.

Renan Souza
  • 905
  • 9
  • 25
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);
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
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);
imfsilva
  • 139
  • 8