Reputation: 1108
I have the following javascript code:
console.log("Line: 89");
console.log(products[i]['barcodes'][j]);
console.log(barcode);
console.log(barcode == products[i]['barcodes'][j]);
console.log(barcode == 888);
console.log(products[i]['barcodes'][j] == 888);
console.log(888 == 888);
And I'm seeing the following output in the console
Line: 89
888
888
false
true
true
true
How is it remotely possible that barcode == products[i]['barcodes'][j]
evaluates to false? How am I supposed to compare these two values?
Upvotes: 2
Views: 80
Reputation: 106385
Consider the following:
var a = '888';
var b = '888 ';
console.log(a); // 888
console.log(b); // 888
console.log(a == b); // false
console.log(a == 888); // true
console.log(b == 888); // true
When you compare a
and b
, they are both strings - and are compared directly, without any typecast. So whitespace at the end of b
does matter here.
However, when you compare both a
and b
to number 888, the strings stored in these variables are first converted to a number (where the trailing whitespace at the end of '888 '
is ignored) before being compared.
Upvotes: 3
Reputation: 7346
Javascript types can be flaky, and most likely the types are different. You'll have to do something to equalize the types such as
parseInt(barcode) == parseInt(products[i]['barcodes'][j])
Upvotes: -2
Reputation: 2288
Well, since we don't know what either of those two variables are we can't say. However we can guess that they are not both integers.
From MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
If the two operands are not of the same type, JavaScript converts the operands, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
Upvotes: 1