I ran across this bit of code today:
if (request.body.body.trim() === '') {
return response.status(400).json({ body: 'Must not be empty' });
}
This actually made me pause. It seemed unnecessary to me. Like... why? I could easily just use something like:
if (request.body.body === '') {...}
To check for empty fields, right?
But the use of trim()
is actually pretty smart. trim()
returns a string without spaces at the start or end. Thus, for example:
let trimmy = " foo. "
let trimmier = " bar "
console.log(trimmy.trim() + trimmier.trim())
//foo.bar
So, why use trim()
? To prevent the submission of " "
or or any number of empty spaces to the database. Pretty slick.
" ".trim()
will return ""
Cool, huh?
Top comments (0)