5

I am learning Javascript with codecademy, and I was doing some comparisons, and for my code I did:

`console.log(1 == 2)`

and it returned False. I also did:

`console.log(2*2 === 3)`

and that also returned False. To check that I have not made a mistake, I did:

`console.log(1 == 1)`

and that returned True The instructions tell me that === means equal to.

Are there any problems with using == instead of ===? And, which is better to use and why?

Thanks for any help you can give me!

George
  • 330
  • 1
  • 8
  • 19
  • Sorry for the duplicate, I should really search more, I don't mind if you mark it as duplicarte or close it – George Jul 14 '13 at 20:24

3 Answers3

4

Using == compares only the values, === compares the type of the variable also.

1 == 1 -> true
1 == "1" -> true
1 === 1 -> true
1 === "1" -> false, because 1 is an integer and "1" is a string.

You need === if you have to determine if a function returns 0 or false, as 0 == false is true but 0 === false is false.

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
  • 2
    They both compare the types. The difference is that the `==` *coerces* the values to matching types when the types don't match. –  Jul 14 '13 at 20:08
  • But it makes no difference, does it? – Lars Ebert Jul 14 '13 at 20:13
  • 4
    Only in correctly understanding what happens. Say the `===` compares the types, and finds different types, so it just return `false`. But then if the `==` doesn't compare types, but only values, the values still don't match. What happens is that they both start by comparing types, and they both behave the same when the types match. But when the types don't match the `===` gives up, but the `==` begins the process of type coercion, making a recursive comparison every time a type is changed. Eventually the operands are reduced to the same type, and you get your value comparison. –  Jul 14 '13 at 20:32
3

It really depends on the situation. It's usually recommended to use === because in most cases that's the right choice.

== means Similar while
=== means Equal. Meaning it takes object type in consideration.

Example

'1' == 1 is true

1 == 1 is true

'1' === 1 is false

1 === 1 is true

When using == it doesn't matter if 1 is a Number or a String.

Community
  • 1
  • 1
Shawn31313
  • 5,978
  • 4
  • 38
  • 80
2

http://www.w3schools.com/js/js_comparisons.asp

== is equal to || x==8 equals false

=== is exactly equal to (value and type) || x==="5" false

meaning that 5==="5" false; and 5===5 true

After all, it depends on which type of comparison you want.

calexandru
  • 307
  • 1
  • 3
  • 16