When and why should we use '===' in javascript or jquery. Is it recommended to test string using === and if yes why. I have a code where i am checking a condition on the string like. if(a == "some-thing") is this right or should i use '==='
7 Answers
===
means exactly equal - compare value and type.
'1' == 1 // true
'1' === 1 // false

- 41,402
- 5
- 66
- 96
===
is used for strictly type check, when you want to check value as well as its type.
For Example
var x = 5;
var y = "5";
var z=5;
alert(x==y);//string and int value same though type different - TRUE
alert(x===y);//value same but type different - FALSE
alert(x===z);//value same and type same- TRUE

- 28,279
- 5
- 35
- 57
with ===
you will compare the value AND the type of data. With ==
you only compare the value. So 1000 == "1000"
it's true, while 1000 === "1000"
is false.

- 21,869
- 4
- 38
- 69
In a simple answer:
Triple equals does a check for type equality. So it'll check the types as well as the contents.
e.g.
var a = '1' === 1;
Would be false.
A double equals would only check the contents, so the code above would return true.

- 426
- 3
- 8
As a good practice, as much as possible.
As a minimum : if you want to check specifically for 0/false/null value because when you use ==
they're all the same :
0 == false // true
0 === false // false
And f you test the existence of a value but that value can be false or 0 this won't work.
if(value){} // false is value === false or value === 0
There is also the type equality but i don't really think that much relevant unless you depend on some 3rd-party where you need this.

- 5,363
- 1
- 16
- 35
A === "some string" means equal value and moreover equal type.
It's a double test: In your case you obtain true not simply if the values are equal but moreover if the variable A is a string.

- 41,594
- 6
- 42
- 61
You should almost always use the === operator.
An example why:
1 == '1' //is true
1 === '1' //is false
And you want to achieve the second result, because === checks if also the type is the same.

- 451
- 6
- 17
-
2Not always. That's not true – Marcos Pérez Gude Apr 18 '16 at 08:02
-
What if from GET you receive string and from databse you receive integer? Same values, but `===` will ruin things – Justinas Apr 18 '16 at 08:02
-
Why do you always need to check the type? JavaScript is not type sensitive and the function is added for a reason. – Zorken17 Apr 18 '16 at 08:08