JavaScript question #Day 8

What’s the output ?

function checkAge(data) {
if (data === { age: 18 }) {
console.log(‘You are an adult!’);
} else if (data == { age: 18 }) {
console.log(‘You are still an adult.’);
} else {
console.log(`Hmm.. You don’t have an age…


This content originally appeared on DEV Community and was authored by Sooraj S

What's the output ?

function checkAge(data) {
  if (data === { age: 18 }) {
    console.log('You are an adult!');
  } else if (data == { age: 18 }) {
    console.log('You are still an adult.');
  } else {
    console.log(`Hmm.. You don't have an age I guess`);
  }
}

checkAge({ age: 18 });
  • A: You are an adult!
  • B: You are still an adult.
  • C: Hmm.. You don't have an age I guess

Answer: C

When testing equality, primitives are compared by their value, while objects are compared by their reference. JavaScript checks if the objects have a reference to the same location in memory.

The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality.

This is why both { age: 18 } === { age: 18 } and { age: 18 } == { age: 18 } return false.


This content originally appeared on DEV Community and was authored by Sooraj S


Print Share Comment Cite Upload Translate Updates
APA

Sooraj S | Sciencx (2021-07-18T12:52:36+00:00) JavaScript question #Day 8. Retrieved from https://www.scien.cx/2021/07/18/javascript-question-day-8/

MLA
" » JavaScript question #Day 8." Sooraj S | Sciencx - Sunday July 18, 2021, https://www.scien.cx/2021/07/18/javascript-question-day-8/
HARVARD
Sooraj S | Sciencx Sunday July 18, 2021 » JavaScript question #Day 8., viewed ,<https://www.scien.cx/2021/07/18/javascript-question-day-8/>
VANCOUVER
Sooraj S | Sciencx - » JavaScript question #Day 8. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/18/javascript-question-day-8/
CHICAGO
" » JavaScript question #Day 8." Sooraj S | Sciencx - Accessed . https://www.scien.cx/2021/07/18/javascript-question-day-8/
IEEE
" » JavaScript question #Day 8." Sooraj S | Sciencx [Online]. Available: https://www.scien.cx/2021/07/18/javascript-question-day-8/. [Accessed: ]
rf:citation
» JavaScript question #Day 8 | Sooraj S | Sciencx | https://www.scien.cx/2021/07/18/javascript-question-day-8/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.