Like maybe I am missing something here, but in Step 40 of ‘Learn Basic String and Array Methods by Building a Music Player,’ there is a note that states: ‘You should not use the optional chaining operator ?. in this step because userData.currentSong will not be null or undefined at this point,’ which leads me to believe that optional chaining should only be used if a value could potentially be null or undefined.
However, in step 43, I am told “add an if to check if userData?.currentSong is null”
Further, in step 44, I am told to add an else block and call the playSong function “with the id of the currently playing song as an argument”, so my code is supposed to look like this:
if (userData?.currentSong === null) {
playSong(userData?.songs[0].id);
} else {
playSong(userData?.currentSong.id)
}
While I do get that we would need to use optional chaining for the playSong block (playSong(userData?.songs[0].id);)*, I do not get why we need to use optional chaining for the other two blocks:
At the start of our code, we initialized userData like this:
let userData = {
songs: […allSongs],
currentSong: null,
songCurrentTime: 0,
};
meaning it will always exist, even if all songs are deleted, so it will never be undefined.
Also, for the playSong with currentSong block(playSong(userData?.currentSong.id)), I don’t see why we need optional chaining here either, given that the if condition before this ensures currentSong is not null or undefined in the else block, therefore valid.
Currently,
if (userData.currentSong === null) {
playSong(userData?.songs[0].id);
} else {
playSong(userData.currentSong.id)
}
is not accepted and I am wondering what is the purpose here, assuming that “When in doubt, use optional chaining” is not a valid approach. (Google seems to think it isn’t, and trying to understand why in step 44 “playSong(userData.currentSong.id)” was not accepted is what got me confused. Did at first not note it in step 43, as it explicitly tells me to “call the playSong() function with the id of the first song in the userData*?**.songs* array.”, but in step 44, it does not say that, so I can’t see a reason why we need to use optional chaining here…)
PS: There seem to be an additional 3 or 4 cases where optional chaining is used, but it appears to me that it would not be needed.
Any insights would be great as to why it is the way it is currently.
- Optional chaining is necessary because the user has the option to delete all songs, and than the songs[0] property will not exist, which will cause an error.