Why eval("475957E-8905") == "475957E-8905" is true? - javascript

I made a program with nodeJs which generate code such as
eval("XXXXXX") == "XXXXXX"
It's working pretty well, but at a moment he gave me this :
eval("475957E-8905") == "475957E-8905"
I tested it with Firebug, and the result is true
.But I don't really understand why.
Of course, eval("475957E-8905") return 0
but why 0 == "475957E-8905" ?

There are two pieces to this puzzle: floating-point numbers and type-insensitive comparison using ==.
First, 475957E-8905 evaluates as the floating point number 475957 * 10 ^ -8905, which is incredibly small; in floating-point terms, it's the same as 0 due to the precision limitations of javascript. So, eval("475957E-8905") returns 0.
Now, for the second piece of the puzzle.
The == means that the types don't have to match, so nodejs (like any JavaScript engine) tries to convert one of them so it can compare them.
Since eval("475957E-8905") returned 0, it tries to convert "475957E-8905" to an integer as well. As we have seen, that is also 0. Thus, the comparison is 0 == 0, which is true.
Note that the same thing happens if you do eval("3") == "3" or eval("3") == 3 -- in each case, the strings are converted to numbers and compared.
Avoiding this problem
You can force a type-sensitive comparison like this:
eval("475957E-8905") === "475957E-8905"
which returns false, because the === tells the javascript engine to return true only if the types and the values both match.

Javascript has to convert your string, "475957E-8905", to a number in order to compare them. When it does that, it converts "475957E-8905" to 0 as well. So, 0 == 0;
As you can see:
"475957E-8905" == 0
Is true. Basically you eval statement "475957E-8905" into a number, and then the other "475957E-8905" is being converted to a number for comparison. In the end, the exact same conversion process has happened to both of them and they are both 0.

use === to compare the type as well, for further information:
JavaScript has both strict and
type-converting equality comparison.
For strict equality the objects being
compared must have the same type and:
Two strings are strictly equal when they have the same sequence of
characters, same length, and same
characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have
the same number value). NaN is not
equal to anything, including NaN.
Positive and negative zeros are equal
to one another.
Two Boolean operands are strictly equal if both are true or
both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]
check this documentation

Related

In which cases should `==` be used over `localeCompare` and viceversa, in Javascript?

What are the pros and cons of each of them when compared to each other?
In which cases should == be used over localeCompare and viceversa, in Javascript?
They are not at all the same!
Non-strict comparison compares strings to see if they are the same (only included strings as that's what localeCompare works on, types are irrelevant).
"test" == "test" // true
localCompare is a lot more than that, it returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order, and in the specified language.
'a'.localeCompare('c') // returns a negative value, i.e. -1 etc, a comes before c
'a'.localeCompare('a') // returns 0, they are the same
'c'.localeCompare('a') // returns a positinve value, i.e. 1 etc, c comes after a
note that the sort order used is entirely implementation dependent, but in most browsers it will be alphabetical
or language specific
'ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z
As it return a negative integer, zero or a positive integer, it's useful in functions such as sort() which expects the return of the sorting callback to be just that, a negative integer, zero or a positive integer.
MDN
localeCompare is not the same as ==. When you compare two variables using ==, you check whether or not the variables have the same content. This will return a boolean (true/false). However, localeCompare does not return a boolean but an int instead.
You will receive a 0 when the two variables are the same, but you will however receive either 1 or -1 if your variables are not the same. The value is based on whether the first variable comes before or after the second variable in sort order.
So I myself would use == when I'm purely validating if two variables are the same, but localeCompare can become handy when you want to see what variable comes first in sort order, however it can be used to compare two variables to see if they are the same.
string a = "hello";
string b = "world";
a == b // returns false
a.localeCompare(b); // returns -1
To answer your question slightly, these are the characteristics / pro's and cons of using either of the examples given:
Using ==
Returns a boolean instead of a string/integer/...
Easier to read by most people
Using localeCompare
Returns an integer (-1, 0 or +1)
Can be used to sort variables
localeCompare doesn't just check for equality in value. It also compares the values when they're different, and returns a 1 / -1 depending on which value is higher. It's return value is in no way similar to a equality check.
localeCompare can be used for sorting strings, as the return value is different from == when the 2 values aren't the same, == can only be used for determining equality (in value, not type).
For example:
"2".localeCompare(2) // 0
"2".localeCompare(1) // 1
"2".localeCompare(3) // -1
"2" == 2 // true
"2" == 1 // false
"2" == 3 // false
"b".localeCompare("b") // 0
"b".localeCompare("a") // 1
"b".localeCompare("c") // -1
"b" == "b" // true
"b" == "a" // false
"b" == "c" // false
The return value from localeCompare happens to be exactly what Array.prototype.sort() expects to be returned from it's handler.
localeCompare is very useful to implement a sorting (ascending or descending) function:
myLabelsArray.sort(function(a, b){
return a.label.localeCompare(b.label);
});
Indeed, localeCompare returns -1, 0 (if equals) or 1 (based on locale language rules), allowing to get a sorting.
It would take more lines to implement it with == + <, explicitly returning integers.

Javascript 0 == '0'. Explain this example

I found these examples in another thread but I don't get it.
0 == '0' // true
0 to the left I converted to false(the only number that does that). The right is a non empty string which converts to true.
So how can
false == true --> true
What have I missed?
Here is an official answer to your question (the quoted parts, link at the bottom) and analysis:
Equality (==)
The equality operator converts the operands if they are not of the same type, 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.
Syntax
x == y
Examples
3 == 3 // true
"3" == 3 // true
3 == '3' // true
This means, as I read it, that the first 3 (integer) is converted to string to satisfy the comparison, so it becomes '3' == '3', which is true, same as in your case with zeroes.
NOTE: I assume that the converion may vary in different JS engines, although they have to be unified under ECMAScript specifiction - http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 (quoted #Derek朕會功夫). This assumption is made on a subjective and imperative opinion that not all browsers and JavaScript engines out there are ECMAScript compliant.
Identity / strict equality (===)
The identity operator returns true if the operands are strictly equal (see above) with no type conversion.
The Identity / strict equality (===) found on the same resource at the end of the answer will skip the automatic type conversion (as written above) and will perform type checking as well, to ensure that we have exact match, i.e. the expression above will fail on something like:
typeof(int) == typeof(string)
This is common operator in most languages with weak typing:
http://en.wikipedia.org/wiki/Strong_and_weak_typing
I would say that one should be certain what a function/method will return, if such function/method is about to return numbers (integers/floating point numbers) it should stick to that to the very end, otherwise opposite practices may cut your head off by many reasons and one lays in this question as well.
The above is valid for other languages with weak typing, too, like PHP for example.
Read more of this, refer second head (Equality operators):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
When you use == JavaScript will try very hard to convert the two things you are trying to compare to the same type. In this case 0 is converted to '0' to do the comparison, which then results in true.
You can use ===, which will not do any type coercion and is best practice, to get the desired result.
Equality operator
The equality operator converts the operands if they are not of the same type, 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.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
JavaScirpt Table Equality: http://dorey.github.io/JavaScript-Equality-Table/

A javascript statement that I haven't seen before

I am inspecting some Javascript code written in UnderscoreJS. In this, there are quite a few instances of JS code being written like this:
if(length === +length){ //do something}
or
if(length !== +length){ //do something }
What exactly does this compute to? I have never seen this before.
if (length === +length)
It makes sure that the length is actually a numeric value.
Two things to understand here,
The Strict equality operator, will evaluate to true only when the objects are the same. In JavaScript, the numbers and strings are immutables. So, when you compare two numbers, the Number values will be compared.
Unary + operator will try to get the numeric value of any object. If the object is already of type Number, it will not make any changes and return the object as it is.
In this case, if length is actually a number in string format, lets say "1", the expression
"1" == +"1"
will evaluate to be true, because "1" is coerced to numeric 1 internally and compared. But
"1" === +"1"
which will be transformed to
"1" === 1
and that will not undergo coercion and since the types are different, === will evaluate to false. And if length is of any other type, === will straight away return false, as the right hand side is a number.
You can think of this check as a shorthand version of this
if (Object.prototype.toString.call(length) === "[object Number]")
It is a way of testing whether a value is numeric. See this for example:
> length="string"
> length === +length
false
> length=2
> length === +length
true
The unary + converts the variable length to the Number type, so if it was already numeric then the identity will be satisfied.
The use of the identity operator === rather than the equality operator == is important here, as it does a strict comparison of both the value and the type of the operands.
Perhaps a more explicit (but slightly longer to write) way of performing the same test would be to use:
typeof length === "number"

How does JavaScript evaluate if statement expressions?

I always thought that JavaScript's if statements did some kind of casting magic to their arguments, but I'm a little wary of what's actually going on behind the scenes.
I recently found a JavaScript comparison table and noticed that even though -1 == true evaluates to false, if(-1){...} will execute.
So within JavaScripts if statements, what happens to the expression? It seems reasonable to assume that it uses !!{expression} to cast it to an inverse boolean, then invert it again, but if that's the case, how does JS decide whether an object's inverse boolean representation is truthy or not?
JavaScript is wonky.
Yes, -1 == true results in false, but that's not what the if statement is doing. It's checking to see if the statement is 'truthy', or converts to true. In JavaScript, that's the equivalent of !!-1, which does result in true (all numbers other than zero are truthy).
Why?!?
The spec defines the double equals operator to do the following when presented with a number and a boolean:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
ToNumber will convert the boolean true into the number 1, so you're comparing:
-1 == 1
which anyone can tell you is clearly false.
On the other hand, an if statement is calling ToBoolean, which considers any non-zero, non-NaN number to be true.
Any JavaScript developer really needs to look at the documentation -- for this case, located here: http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
9.2 ToBoolean
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
Object true
(Sorry about the formatting, can't make a table here.)
From JavaScript The Definitive Guide
The following values convert to, and therefore work like, false:
undefined
null
0
-0
NaN
"" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true. false, and the six values that convert to it, are sometimes called falsy values, and all other values are called truthy.
These things by themselves are falsy (or evaluate to false):
undefined
null
0
'' or ""
false
NaN
Everything else i truthy.
Truthy-ness or falsy-ness is used when evaluating a condition where the outcome is expected to be either truthy (true) or falsy (false).
In your example if(-1 == true), you are comparing apples and oranges. The compare is evaluated first (and resulted in false), and the results of that is used in your condition. The concept of truthyness/falsyness isn't applied to the operands the comparison.
When if state using with comparing variable different type js use .toString и .valueOf ( for more information check http://javascript.info/tutorial/object-conversion ) - just keep this in mind - it make so example much more easy to understand

Javascript equality triple equals but what about greater than and less than?

I was explaining to a colleague that you should use === and !== (and >== and <== of course) when comparing variables in JavaScript so that it doesn't coerce the arguments and get all froopy and confusing but they asked me a two part question that I did not know the answer to and thought I would ask the experts here, specifically it is:
What about > and < - when they compare do they also coerce the arguments or not - why isn't there some sort of >> and << operator (probably need to be some other syntax as I would guess they would be bit shift operators if it is going along the whole C style but you get the gist)?
So I can write a test to find the answer to the first part, which I did, here it is:
// Demo the difference between == and ===
alert(5 == "5");
alert(5 === "5");
// Check out what happens with >
alert(5 > "4");
alert(5 > 4);
and it returned:
true
false
true
true
so it does look like the > is doing the coercion since > "4" and > 4 return the same result. so how about the second part...
Is there some sort of operator for > and < that do not coerce the type (or how can I change my test to perform the test safely)?
No, there's no need for such operators. The type checking done for those relational operators is different than for equality and inequality. (edit — perhaps it's a little strong to say that there's "no need"; that's true only because JavaScript deems it so :-)
Specifically, the > and < and >= and <= operators all operate either on two numeric values, or two strings, preferring numeric values. That is, if one value is a number, then the other is treated as a number. If a non-number can't be cleanly converted to a number (that is, if it ends up as NaN), then the result of the comparison is undefined. (That's a little problematic, because undefined will look like false in the context of an if statement.)
If both values are strings, then a collating-order string comparison is performed instead.
If you think about it, these comparisons don't make any sense for object instances; what does it mean for an object to be "greater than" another? I suppose, perhaps, that this means that if you're finding yourself with values of variant types being compared like this, and that's causing problems, then yes you have to detect the situation yourself. It seems to me that it would be good to work upstream and think about whether there's something fishy about the code that's leading to such a situation.
Is there some sort of operator for > and < that do not coerce the type
No.
how can I change my test to perform the test safely
You would have to explicitly test the types:
typeof a === typeof b && a > b
I referenced Flanagan's JavaScript: The Definitive Guide (5th Ed.) and there does not seem to be non-coercive comparison operators.
You are right in saying the << and >> are indeed bitwise operators so that wouldn't work.
I would suggest you deliberately coerce the values youself:
var num_as_string = '4';
var num = +num_as_string;
if (5 > num) { ... }
12 > '100' // false
'12' > 100 // false
'12' > '100' // true
As others mentioned, if one is a number the other is casted to a number. Same rule applies to these cases as well:
null > 0 // false
null < 0 // false
null >= 0 // true
However, there might be cases that you would need null >= 0 to give false (or any of the number string comparison cases above), therefore it is indeed a need to have strict comparison >== or <==.
For example, I am writing a compareFunction for the Array.prototype.sort() and an expression like x>=0 would treat null values like 0's and put them together, whereas I want to put them elsewhere. I have to write extra logic for those cases.
Javascript says deal with it on your own (in practice).

Categories

Resources