function hi(cartoon_character) {
if (cartoon_character == { name: 'Mickey' }) {
return 'Hey Mickey'
} else {
return 'Hey Mouse'
}
}
document.write(hi({ name: 'Mickey' }));
why the result is "Hey Mouse" should be "Hey Mickey"
function hi(cartoon_character) {
if (cartoon_character == { name: 'Mickey' }) {
return 'Hey Mickey'
} else {
return 'Hey Mouse'
}
}
document.write(hi({ name: 'Mickey' }));
why the result is "Hey Mouse" should be "Hey Mickey"
Here you are comparing the memory locations(references) and hence the result is always Hey Mouse. A quick workaround could be:
function hi(cartoon_character) {
if (JSON.stringify(cartoon_character) ===
JSON.stringify({ name: 'Mickey' })) {
return 'Hey Mickey'
} else {
return 'Hey Mouse'
}
}
console.log( hi({name: 'Mickey'}) )
For better understanding have a look https://medium.com/javascript-in-plain-english/comparing-objects-in-javascript-ce2dc1f3de7f#:~:text=Comparing%20objects%20is%20easy%2C%20use,obj2)%3B%20would%20return%20false.