Why are these two lines == but not ===

I know that I will feel stupid at the end of this, but I struggled with this ...

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

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

Substituting === , my test fails, generating console output, for example:

'56e0a2085b89105924963dc3' does not match '56e0a2085b89105924963dc3'

I think that ticks ' prove that there are no spaces at both ends. This article states that either the types do not match, or that one of the strings was created using the new String constructor, but I do not control the code that generates them. What should I do?

  • turn them into something else for comparison? ... yuck, and why?
  • suppress or ignore jshint? ... what as a lazy developer gets into trouble later
  • debug more? ... but how? I don’t even know how to register the type of object (in JS, which seems to be a whole other long trip through a weird oddity).
+5
source share
1 answer

It looks like you are using mongodb to get the objectId (I assume from the syntax). You should check if user._id is actually a string instead of an ObjectId. You can pause execution or simply use the typeof operator to see if user._id is really a string.

+6
source

Source: https://habr.com/ru/post/1244773/


All Articles