-2

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 '==='

HEraju
  • 77
  • 3

7 Answers7

1

=== means exactly equal - compare value and type.

'1' == 1 // true
'1' === 1 // false
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

=== 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

More Information

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

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.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

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.

Mike Palfrey
  • 426
  • 3
  • 8
0

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.

Walfrat
  • 5,363
  • 1
  • 16
  • 35
0

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.

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
-3

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.

notme
  • 451
  • 6
  • 17