Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use == or === In Javascript? [duplicate]

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!

like image 520
George Avatar asked Jul 14 '13 20:07

George


3 Answers

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.

like image 123
Lars Ebert Avatar answered Oct 08 '22 22:10

Lars Ebert


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.

like image 41
Shawn31313 Avatar answered Oct 08 '22 21:10

Shawn31313


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.

like image 35
calexandru Avatar answered Oct 08 '22 23:10

calexandru