Ternary vs if .. else

Tell us what’s happening:
Describe your issue in detail here.
Hi, eventually i’m missing something, yet can’t figure out myself.
Below in code section there is

  • a working solution (rows 5-10, using if…else)
  • and a try to make it shorter using ternary operator (rows 12-13)
    • which evaluated to ‘undefined’. Can’t make it up to work with ternary. My guess is for return statement that stops function with if…else approach. But i’d appreciate a hand here :pray:.
      Thanks

      Your code so far


function checkObj(obj, checkProp) {
// Only change code below this line

// below does the job as expected
if (obj.hasOwnProperty(checkProp)) {
  return obj[checkProp]
} else {
  return 'Not Found'
}

// tried to tidy-up the code with ternary operator, but it returns 'undefined'
// obj.hasOwnProperty(checkProp) ? obj[checkProp] : 'Not Found'

// Only change code above this line
}

console.log(checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift"))
  **Your browser information:**

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

Challenge: Testing Objects for Properties

Link to the challenge:

You’re not returning anything.

The main reason for using the ternary is that it’s an expression, it’s not a statement like if else. You have to return that expression.

3 Likes

You should include a return keyword before your ternary expression

🙇‍♂️ thank you @ [DanCouper] and @ [devmariam]
i’ve realized this just today morning like 3 mins before checking back this topic ))
Be blessed :palms_up_together:

1 Like

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