-1

I want to check whether the value in an input box is equal to a variable. When I use ===, it returns false but when I use ==, it returns true, provided both are equal.

<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1;
d1 = Math.floor(Math.random()*100)
if( document.getElementById("g1").value ==  d1) {
document.getElementById("d").innerHTML = "Correct";
}
Moltres
  • 600
  • 4
  • 21

4 Answers4

2

This happens because JavaScript == can compare numeric strings to numbers whereas === does not.

Similarly the "value" property your using returns a string that you're comparing to an integer. You'll need to use parseInt to convert the value first.

parseInt(document.getElementById("g1").value) ===  d1

A few things to consider with parseInt:

  • parseInt returns NaN when you try to convert non-number strings (i.e. converting 'bogus' returns NaN.
  • It will convert decimals into integers by dropping the decimals. So parseInt('2.1') == 2 // => true.

Honestly, given your use case, it's appropriate to use ==, but I'd add a comment explaining why it's being used.

fny
  • 31,255
  • 16
  • 96
  • 127
1

=== means both value has to be equals but have same type of data in it aswell where == means they only needs to be equal. so for example if d1 is a string holding value 2 and g1 is an integer also holding value 2 using === would not work and will return false as both data is different even though they have same syntax.

<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1 = 0;
d1 = Math.floor(Math.random()*100)
if( paseint(document.getElementById("g1").value) ===  d1) {
    document.getElementById("d").innerHTML = "Correct";
 }
  • The way the code is its fine, but if you want to use === then make sure to convert both data to integer. –  Aug 18 '17 at 15:49
  • As the answer above parseInt(document.getElementById("g1").value) === d1 –  Aug 18 '17 at 15:50
0

== is the equality operator === is an identity operator

For example true==1 is true because true is converted to 1 and then it's compared. However, true===1 is false. This is because it does not do type coercion.

That aside, in your case I think you want to try casting your value to an integer and then compare.

0
var string5 = '5'
var numb5 = 5
if (string5 == numb5) will  return true
if (string5 === numb5) will  return false

second variant also compares type, because string is not same type as number it is false.