Basic JavaScript - Record Collection Using ? Operator

Good day,

So I’ve been doing basic javascript lessons and ran into a roadblock. Im using the ? operator instead of “if else” for the solution, and it worked when I tested it.
In console, the output for console.log(recordCollection[5439]) is
{ albumTitle: ‘ABBA Gold’, artist: ‘ABBA’ }
But it won’t accept my answer. It says artist should be string ‘ABBA’. Can someone help?

Here’s my code

// Setup
const recordCollection = {
  2548: {
    albumTitle: 'Slippery When Wet',
    artist: 'Bon Jovi',
    tracks: ['Let It Rock', 'You Give Love a Bad Name']
  },
  2468: {
    albumTitle: '1999',
    artist: 'Prince',
    tracks: ['1999', 'Little Red Corvette']
  },
  1245: {
    artist: 'Robert Palmer',
    tracks: []
  },
  5439: {
    albumTitle: 'ABBA Gold'
  }
};

// Only change code below this line
function updateRecords(records, id, prop, value) {
  return value == "" ? 
    delete records[id][prop]
  : prop !== 'tracks' && value !== "" ? 
    records[id][prop] = value
  : prop == 'tracks' && value !== "" ?
    records[id].hasOwnProperty("tracks") == false ?
      records[id][prop] = [value]
    : records[id][prop].push(value)
  : "Error";
}


updateRecords(recordCollection, 5439, 'artist', 'ABBA');

console.log(recordCollection[5439])

Thank you

This is a bad way to use a ternary. A ternary is not a general purpose replacement for an if statement.

I see, I was practicing doing ternary by doing some javascript lesson using it, so I haven’t grasped on when or when not to use ternary. That being said, is there a mistake with the code above? Or should I change it to if else?

In this case you should use if-else.

Generally, you should only use a ternary to set a value based upon a condition. Something like

const myValue = (cat > dog) ? "I love cats" : "I love dogs";

Here, your complex chain of ternaries is giving a ton of different return values, none of which are the entire records object.

So that’s how it is, thank you very much for explaining

1 Like

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