-5

When i tried out the following in the google Chrome console , i got the corresponding answers can anyone explain reason for the following answers

1 == '1.0'
true

1 == '1'
true 

'1.0' == '1'
false

Why is this happening and does this means , == compares value or not

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
Sree
  • 1,694
  • 1
  • 18
  • 29
  • 3
    d u p l i c a t e so many times, oh javacript you cruel master you – NimChimpsky Jun 18 '14 at 12:52
  • 1
    Come on! http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 – dfsq Jun 18 '14 at 12:53
  • the final example is false because it is the same as saying ('one point one' == 'one') which is clearly not true. Numbers in a string are not counted as vales, but as text. (I am not saying that my example is the same as the example used, but they are equivalent) – Sam Denton Jun 18 '14 at 12:59

3 Answers3

2

Javascript == operator tries to convert each side to the same type before making comparison. That is why;

1 == '1.0' true (converts '1.0' to int first)

1 == '1' true (same here)

'1.0' == '1' false (they are both of same type but different string value)

Use the === operator if you do not want type conversion.

Laçin Yavuz
  • 106
  • 3
2

In the first two comparisons, the string is automatically converted to an integer. So you basically compare 1 == 1 which is true.

The last comparison is not converted as you don't give any integer. So you are comparing two strings whcih are not the same. So this results in false.

A nice blog post about automatic conversion in javascript comparisons can be found here: http://webreflection.blogspot.de/2010/10/javascript-coercion-demystified.html

Tobbe
  • 121
  • 5
1

Quite simply because you are comparing two strings. The string

"1.0" is not the same as "1"

When you do the following, the right hand side gets cast to a number before the comparison, hence it results in a value fo true.

1 == '1.0'

If you want to prevent this cast, use triple equals

1 === '1.0'
Ian
  • 33,605
  • 26
  • 118
  • 198
  • that answers one of the questions, so why does 1 = "1" evaluate to true, when the types are different, And in a static language would be false ? Hwo do you ensure you don't implicitly perform type coercion ? – NimChimpsky Jun 18 '14 at 12:55
  • @NimChimpsky: Which bit doesn't it answer? I'll update – Ian Jun 18 '14 at 12:55
  • so you are explaining type coercion, and the use of triple equals. But this isn't a duplicate question ? Its probably one of the most duplicated question on stack, with a rep of 13k you should know this. – NimChimpsky Jun 18 '14 at 12:58
  • @NimChimpsky: I mis-read the question originally and missed the initial type coercion. I deleted my comment a little while ago. – Ian Jun 18 '14 at 12:59
  • doesnt; change the fact that this should be marked as duplicate and not answered. – NimChimpsky Jun 18 '14 at 13:00