Still new to JavaScript, I recently encountered this code snippet. How exactly did the function impact the final result? What confuses me is that the function is defined and immediately called ( pet.toJSON() << Something similar to this ). So how does it actually work? Lastly, what is the specific name of this function or where can I find resources to better understand it? Apologies if these questions seem basic, but your explanation would greatly benefit my learning process. Wishing you a wonderful day!
const pet = {
name: 'Marek'
}
pet.toJSON = function () {
return {}
}
console.log(JSON.stringify(pet)) // the result is {}
userSchema.methods.toJSON = function () {
const user = this
const userObject = user.toObject()
delete userObject.password
delete userObject.tokens
return userObject
}