?. in music player, real use

const playPreviousSong = () =>{
   if (userData?.currentSong === null) return;
   else {
    const currentSongIndex = getCurrentSongIndex();
    const previousSong = userData?.songs[currentSongIndex - 1];

    playSong(previousSong.id);
   }
};

i ask chatGPT about acessing an array with a negative number

const a = [1,2,3,4]

console.log(a[-1])

it return undefined, but the music player still working fine , when u first click the previous button after u reload the page

i would assume the music player didnt crash because of the ?.

currentSongIndex = 0
const previousSong = userData?.songs[currentSongIndex - 1]
                                            
userData?.songs[- 1] 
 the saviour -> ?.

am i right?

the ?. is the optional chaining operator, in this way if something doesn’t have a property it just becomes undefined

2 Likes