Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these two strings == but not ===

Tags:

javascript

I know I'm going to feel dumb at the end of this, but I've been struggling with this...

if (user._id == req.params.id) {
    console.log("match");           
} else {
    console.log("'" + user._id + "' does not match '" + req.params.id + "'");
}

This works, comparing two strings that are the same and finding a match. But my jshint tells me to use this operator === which I understand (from here) to mean that types are also checked.

Substituting the === my test fails, generating console output like;

'56e0a2085b89105924963dc3' does not match '56e0a2085b89105924963dc3'

I think the ticks ' prove that there's no whitespace on either end. That article indicates that either the types don't match or that one of the strings was created with a new String constructor, but I don't control the code that generates these. What should I do?

  1. transform them to something else to compare? ...yuck, and to what?
  2. suppress or ignore the jshint? ...that's how a lazy developer gets in trouble later
  3. debug more? ... but how? I don't even know how to log the type of an object (in JS, that seems to be a whole other long trip through language weirdness).
like image 432
user1272965 Avatar asked Mar 09 '16 22:03

user1272965


1 Answers

It looks like you're using mongodb to get the objectId (I'm assuming from the syntax). You should check whether user._id is actually a string instead of an "ObjectId" object. You can pause execution or just use the typeof operator to see if user._id is actually a string.

like image 53
teaflavored Avatar answered Sep 20 '22 06:09

teaflavored