Read till the end, because nothing is what it seems
What is equality?
Equality means different things in different programming languages. In most modern languages (C# for example), you can define your own terms of what equality means. In others you can't.
Take javascript for example. There are actually two kinds of equality: normal equality and being identical.
To check if two variables or values are equal, you use:
if (a == b) { // ... }
To check if two variables are identical, you use:
if (a === b) { // ... }
Most articles (and even supposedly good books) define the latter comparison as being equal and of the same type. While this over-simplification may be true in the majority of cases, it is very inaccurate, because you have to know what "equal" means. I’m not going to talk about javascript’s normal equality operator (==), because enough has been written about that. I’ll focus on the === operator.
The correct meaning of === is that the 2 operands should be identical. This means they should reference the same object, or, in the case of value types, the values should be the same. Only numbers and booleans are value types. Strings behave as value types, but they are actually reference types.
Bringing this all together, let's look at some examples of equality in javascript:
var a = 1; var b = 1; alert(a == b); // true alert(a === b); // true b = "1"; alert(a == b); // true alert(a === b); // false
These are the obvious ones. Now the more interesting stuff:
var a = [1,2,3]; var b = [1,2,3]; var c = a; alert(a === b); // false (these look equal to me, and of the same type) alert(a === c); // true
Remember I mentioned that strings behave like value types? Now it becomes interesting:
var a = "12" + "3"; var b = "123"; alert(a === b); // returns true, because strings behave like value types
And to make it really interesting:
var a = new String("123"); var b = "123"; alert(a === b); // returns false !! (but they are equal and of the same type)
I thought strings behave like value types? Well, it depends who you ask...
EDIT: As one of the commenters (zihotki) points out, the last example adds another twist to the story. Creating a string using the String() object constructor actually doesn't create a variable of type "string", but of type "object". But you can use the object as a string. If you are unaware of this behavior, you can easily shoot yourself in the foot without knowing it.