What does this line of code do - collection[id][prop] = collection[id][prop] || [];

In the suggested answer, if prop equals “tracks”, and if there is no value, the program is given this instruction to follow:

collection[id][prop] = collection[id][prop] || ;

I can’t work out what it does/ means

Your code so far


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

// Only change code below this line
function updateRecords(id, prop, value) {
if(value === "") delete collection[id][prop];
else if(prop === "tracks") {
  collection[id][prop] = collection[id][prop] || [];
  collection[id][prop].push(value);
} else {
  collection[id][prop] = value;
}
return collection;
}

updateRecords(5439, "artist", "ABBA");

Your browser information:

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

Challenge: Record Collection

Link to the challenge:

Hi,

It means that if the boolean value of collection[id][prop] is false, it becomes an array.

The equivalent is :

if (!collection[id][prop]) {
  collection[id][prop] = [];
}
1 Like

Read this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

You’re right,

More precisely here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2

2 Likes

How can collection[id][prop] = collection[id][prop] || ; be an if statement, if there is no ‘if’ included in that line of code?

And what does the empty square brackets mean here?

If you prefer, it is like a ternary operator, like

collection[id][prop] = collection[id][prop] ? collection[id][prop] : []
1 Like

This is what is called “syntactic sugar”. It’s basically a shorthand provided by the language to make code more readable. Under the covers, it is executed as an if/else statement (as ternaries are).

thank you very much !!! It’s very helful.