The following evaluate to true
:
new Number(2) == 2
new String("2") == "2"
Obviously, but so do the following:
"2" == 2
new Number(2) == "2"
new String("2") == 2
So can someone explain clearly why he following evaluates false
?
new Number(2) == new String("2")
The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result. Unlike the strict inequality operator, it attempts to convert and compare operands that are of different types.
The String constructor is used to create a new String object. When called instead as a function, it performs type conversion to a primitive string, which is usually more useful.
To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false . The RegExp test() method searches for a match between a regular expression and a string.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
Because JavaScript has both primitive and object versions of numbers and strings (and booleans). new Number
and new String
create object versions, and when you use ==
with object references, you're comparing object references, not values.
new String(x)
and String(x)
are fundamentally different things (and that's true with Number
as well). With the new
operator, you're creating an object. Without the new
operator, you're doing type coercion — e.g. String(2)
gives you "2"
and Number("2")
gives you 2
.
What I think ==
is basically does value comparision.
In above all situations it's comparing just values. But in this one
new Number(2) == new String("2")
Both are objects so it doesn't compare values, it tries to compare values of object references. That's why it returns false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With