Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings with Javascript

Tags:

javascript

See the following comparisons:

("a" == "a")
true

(/a/ == /a/)
false

Why do I get different results with the following expressions?

EDIT:

Now I am using just == and still getting the same results.


2 Answers

The literal /a/ is not a string, it's a regular expression object. No two objects are === to each other.

like image 121
Pointy Avatar answered Apr 09 '26 01:04

Pointy


undefined, null, Numbers, Strings literals and Booleans are value types in javascript.

So, they will be compared with their value unlike RegExp(or any other Object for that matter) which is an object, where the comparison takes place on the grounds of reference. So "a" == "a" will return true because the values are same but /a/ == /a/ will return false because the references are different.

like image 37
Amit Joki Avatar answered Apr 08 '26 23:04

Amit Joki