Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcodingchewie
8,764 PointsWhy does a strict comparison operator not work here?
After modifying the code from the video to:
app.get('/quotes/:id', (req, res) => res.status(200).json(data.records.find((quote) => quote.id === req.params.id)))
the strict comparison operator will not return anything if I pass http://localhost:3000/quotes/3406
in the browser or in Postman.
When I modify the line to:
app.get('/quotes/:id', (req, res) => res.status(200).json(data.records.find((quote) => quote.id == req.params.id)))
I'm able to get JSON in Postman and the browser. I know this is a stripped down approach but I'm curious why doesn't the strict comparison work here?
2 Answers
Steven Parker
231,248 PointsAs Steffeni suggested, if one value is a string and the other is a number, the standard comparison will apply conversion for you. The strict comparison operator would consider them to be different no matter what they contain.
Mathew Gries
7,072 PointsTo expand further for anyone that runs into this issue or has this question, check this site https://en.wikibooks.org/wiki/Computer_Programming/Type_conversion
request.params.id is a string type, and the quotes.id is a number type something to watch out for when coding. I have banged my head against the wall a few times because of this.
Steffeni Veren
7,259 PointsSteffeni Veren
7,259 PointsAre they two different types? Strict compares values AND types where as
==
will coerce the types and match if they have the same value.