Solving "Testing Objects for Properties" with a Container Variable then Return as Variable errors

Tell us what’s happening:
Describe your issue in detail here.
So I checked the hint and found the right solution. But I can’t seem to figure out what’s wrong with my current code. (I am a beginner and I learnt basic Java from University this term)
Basically, I created a variable as a container for any string, and this function will return this variable in the end.

I first check if the object owns the property, then if it does, I assign the answer = obj[checkProperty]; if not I assign the answer to “Not Found”
I solely believe that this code will somehow work in Java…? I am not sure. I am a real beginner, I have seen the correct one but instead of creating a container variable “answer”, they just return right away. Whats the catch here? doesn’t it return as a string in the end anyways?

  **Your code so far**
function checkObj(obj, checkProp) {
// Only change code below this line
const answer = "";

if (obj.hasOwnProperty(checkProp)){
  answer = obj[checkProp];
} else if (!obj.hasOwnProperty(checkProp)){
  answer = "Not Found";
return answer;
// Only change code above this line

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Testing Objects for Properties

Link to the challenge:

Hi @Albert_Wang !

Welcome to the forum!

Remember that const variable can not be reassigned a value.

You will need to use let to pass the tests.

But also, hasOwnProperty returns a boolean, so you don’t need this else if to check for false.

You can use an else clause

Hope that helps!

1 Like

Ah, I watched some tutorials and they recommended me to always use const, so I followed them without really understanding the difference. Thank you so much. I will make sure I create the variable properly next time. Also thank you for the I didn’t think about the else if part haha… Thank you so so much!

The reason for that is because if you assign a value to a variable and you know it will not change, then it is good to use const.
That will prevent you from accidentally overriding that variable by trying to assign another value to it later on in your code.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.