Can someone explain it to me?

app.get(‘’, (req, res)=>{

Why do we use the question mark (?) what does this mean?
const q = req.query.q?.toLowerCase() || ‘’;

why do we use the dot (.) what does it mean? when I use it?
const results = animals.filter(animal => animal.type.toLowerCase().includes(q));
res.send(results);
});

how should I translate it to my mind?

The ? is really ?.. It is called optional chaining - look that up for a deeper explanation.

JS doesn’t like trying to access properties of null and undefined - it will throw an error for those. We used to do things like:

let q = ''
if (req.query.q) {
  q = req.query.q.toLowerCase()
}

or

const q = (req.query.q && req.query.q.toLowerCase()) || ‘’;

to avoid trying to call that toLowerCase method if req.query.q was undefined.

Optional chaining takes care of that.

const q = req.query.q?.toLowerCase() || ‘’;

says “if req.query.q is not defined, then you can stop there and let’s just call the whole req.query.q?.toLowerCase() undefined”.

When in doubt, check the docs:

I guess if you had to put it into words, “If everything in this accessor chain is undefined or null, then stop evaluating the chain here and evaluate the whole thing to undefined”.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.