1

I'm missing something if someone can please explain it to me. I'm trying to re-write existing code into the ternary operator way. I'm getting the following console error :

Uncaught SyntaxError: Unexpected token }

which I understand there's a condition not properly formatted which I can't seem to find. So I'm not sure what I'm missing or if I maybe misunderstand something in the filter function? Isn't the ? item.verified === true not suppose to automatically return the objects that's true?

var engagement = "social";
var audience = [{ 'verified': true, 'name': 'Steve'},
                { 'verified': false, 'name': 'Phil'},
                { 'verified': true, 'name': 'Jason'}];
let data = [];

data = audience.filter((item) => {
    (engagement === "social") 
    ? item.verified === true
    : (engagement === 'social-crm') 
    ? item.verified === false 
    : (engagement === 'all')
    ? item
})

The syntax that I understand:

data = audience.filter((item) => {
              if (this.engagement === 'social-crm') {
                return item.verified === true;
              } else if (this.engagement === 'social') {
                return item.verified === false;
              } else if (this.engagement === 'all') {
                return item;
              }
});

Here's the fiddle I've been trying to play around with: https://jsfiddle.net/phfilly/ya73e325/7/

5
  • 4
    "I'm trying to re-write existing code into the ternary operator way." — Don't. As you have noticed, it is hard to understand. Don't make more work for whomever has to maintain your code. They'll hate you for it. That person is likely to be you but 6 months older. Commented Jun 23, 2017 at 8:21
  • Thanks, I understand and feel the same way. However company wants to incorporate standards and told me to change it #death Commented Jun 23, 2017 at 8:22
  • Can you change to this data = audience.filter((item) => (engagement === "social") ? item.verified === true : (engagement === 'social-crm') ? item.verified === false : (engagement === 'all')? item : null) Commented Jun 23, 2017 at 8:22
  • @RobG so in the else I want to return the whole object again. Does that make sense? Commented Jun 23, 2017 at 8:24
  • A filter function expects a truthy or falsey return value. Returning true or item produces the same result. @Quentin best comment ever :) Commented Jun 23, 2017 at 8:30

6 Answers 6

5

Yup. Your syntax isn't right. To understand why your code isn't working, it would help if you were to re-write your if-else statements a bit.

if (this.engagement === 'social-crm') {
    return item.verified === true;
} else if (this.engagement === 'social') {
    return item.verified === false;
} else if (this.engagement === 'all') {
    return item;
}

To this:

if(this.engagement === 'social-crm') { return item.verified === true; }
else {
   if(this.engagement === 'social') {item.verified === false; }
   else {
       if(this.engagement === 'all') {return item;} 
   }
}

Now, ternary operators follow a similar nested fashion.

cond1 ? val1 : ( val2 )

Where val2 => cond2 ? val3 : (val4)

Where val4 => cond3 ? val5 : val6

So, now you can rewrite your expression like this:

this.engagement === 'social-crm' ? item.verified === true : 
    (this.engagement === 'social' ? item.verified === false : 
        (this.engagement === 'all' ?  item : null))

The parenthesis matters here, because it closely mimics the nested if-elses from above.

Also note that for the inner most expression, a return value in the else must be specified. I've set it to null but you can return what you want. Do note this is the actual reason your code was failing. Apologies if the answer was long but I wanted to help you understand nested ternary operators.

Sign up to request clarification or add additional context in comments.

Comments

2

A nested ternary operator looks like this:

something = condition ? nested_condition ? value_if_both_conditions_are_true
    : value_if_nested_condition_is_false : value_if_condition_is_false;

This works even without parentheses, but as others have mentioned, it can be hard to read. Especially when multiple conditions are checked, by use of && or || in the condition parts of this example.

2 Comments

It would be nice to include what happens if they are both false.
In this example, if both are false, the result is the same as when only the first condition is false
1

A ternary operator looks like this:

something = (condition) ? a_value : a_different_value;

You forgot : a_different_value on the last case.

Comments

1

I know this is a response for an old post but people still get here for guidance so this is my suggestion.

For readability, please avoid nested ternary operator or if-else cases. Do instead:

const engagement = "social";
const audience = [{ 'verified': true, 'name': 'Steve'},
                { 'verified': false, 'name': 'Phil'},
                { 'verified': true, 'name': 'Jason'}];
             
const engagementRules = {
      'social-crm': (item) => item.verified === true,
      'social': (item) => item.verified === false,
      'all': () => true, // Returning item directly is redundant for a filter, true is more appropriate
    }
  
const audienceFilter = (item) => {
  const rule = engagementRules[engagement];
  return rule && rule(item);
}

const result = audience.filter(audienceFilter);
  
console.log(result);

Comments

0

Try this

You have to have a Condition for the Ternary operator as pointed by @Quentin

data = audience.filter((item) => { (engagement === "social") ? 
item.verified === true : (engagement === 'social-crm') ? 
item.verified === false : (engagement === 'all')? 
item : null})

Comments

-2

Deep nesting can write in a simpler way like this for ternary if-else

let userName = 'Amoos'
let isStudent = false
let age = 7


userName 
      ? console.log(`User name: ${userName} 😊`) 
      : console.log('Unknow user');
      isStudent ? console.log("Yes, is student 👨‍🎓") 
                : console.log('No, not a student 👨‍🎓');
                (age<18) ? console.log("Younger 👶")
                         : console.log("Elder 😁")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.