0
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"

bereal
  • 32,519
  • 6
  • 58
  • 104
Hayukii_
  • 79
  • 5
  • 2
    It's kind of a subject where you should know more about javascript but you can do `if(cartoon_character.name === 'Mickey')` to check. – halilcakar Jun 29 '20 at 03:28
  • This should answer your question: https://stackoverflow.com/a/33300116/2358409 – uminder Jun 29 '20 at 03:37
  • but why yes, when I fill the parameters with other text. For example name: 'ABCD', the result is still Mickey. while else is not executed – Hayukii_ Jun 29 '20 at 05:11

1 Answers1

1

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.

Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
  • This is somewhat static approach , but if it confirmed the object has name key , then you can try this : function hi(cartoon_character) { var ourObject = {name: 'Mickey'} if(cartoon_character['name'] === ourObject['name']) { return 'Hey Mickey' } else { return 'Hey Mouse' } } – Harmandeep Singh Kalsi Jun 29 '20 at 06:21
  • sorry what if like this, my answer is wrong? `function hi(cartoon_character) { if (cartoon_character.name == 'Mickey') { return 'Hey Mickey' } else { return 'Hey Mouse' } } $("#fixed-soal-no4").html(hi({ name: 'Mickey' }));` – Hayukii_ Jun 29 '20 at 06:24
  • Function you have written is absolutely fine , no issues in that – Harmandeep Singh Kalsi Jun 29 '20 at 06:28
  • thank you, but I want to ask one more thing. Is what I wrote efficient? or is there a more efficient way? thank you @Harmandeep Singh Kalsi – Hayukii_ Jun 29 '20 at 07:03
  • This seems fine to me . Also , if you are ok with the solution provided by me , would you mind accepting the answer and giving upvote for better visibility. – Harmandeep Singh Kalsi Jun 29 '20 at 07:56