Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Detecting if property age exists?

Hi. I'm working on this question:

Consider a object john of class Person. Which of the following is(are) the best way(s) to detect if property age exists?

A. If(john.age){ // do something } B. if ("age" in john) { // do something }

I think that the answer is obviously option 4. But I think I'm possibly missing something or there is a twist to it that I don't see. Any reason options 1, 2 or 3 could be correct?

  1. Both A & B are correct ways to detect if the property age exits for john
  2. Both A & B are incorrect ways to detect if property age exists for john
  3. Choice A is incorrect but choice B is the correct way to detect if property age exists for john
  4. Choice B is incorrect but choice A is the correct way to detect if property age exists for john

1 Answer

You can play around with this in your JavaScript console. This is what my console reports:

var test = {key: "value"}
if (test.key) console.log("true") //Printed "true"
if ("key" in test) console.log("true") //Printed "true"
if (test.missingkey) console.log("true") //Printed nothing
if ("missingkey" in test) console.log("true") //Printed nothing

Since A and B both evaluate to true, answer 1 could be correct.