Using Nullish Coaleshing Operator

The program goes through the days and prints the opening and closing hours for each day. On saturday the situation is different, there is no PM times. So by using ?? I thought the program could switch to the second sentence as on Saturday {openPM} and {closePM} are undefined,but it does not work.

const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];


const  openingHours = {

    [weekdays[1]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[2]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[3]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[4]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[5]]: {
        openAM: 9,
        closeAM: 12,
        //openPM: 0,
        //closePM: 0,
    }
}

const entries = Object.entries(openingHours)

for (let [day, {openAM, closeAM, openPM, closePM}] of entries)
console.log(`the store is open on ${day} from ${openAM} to ${closeAM} and from ${openPM} to ${closePM}` ?? `the store is open on ${day} from ${openAM} to ${closeAM} `)

Answer

Your first template string cannot be null thus your nullish operator can never be in action. So in your case, you probably don’t want to use ?? but the ternary operator ? : to decide which string template to output

const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];


const  openingHours = {

    [weekdays[1]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[2]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[3]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[4]]: {
        openAM: 9,
        closeAM: 12,
        openPM: 15,
        closePM: 20,
    },
    [weekdays[5]]: {
        openAM: 9,
        closeAM: 12,
        //openPM: 0,
        //closePM: 0,
    }
}

const entries = Object.entries(openingHours)

for (let [day, {openAM, closeAM, openPM, closePM}] of entries) {
  let oh = (openPM && closePM)
     ? `the store is open on ${day} from ${openAM} to ${closeAM} and from ${openPM} to ${closePM}`
     : `the store is open on ${day} from ${openAM} to ${closeAM} `
  console.log(oh)
}