Home > Back-end >  Why isn't my nullish coalescing operator (??) working as intended?
Why isn't my nullish coalescing operator (??) working as intended?

Time:12-31

Here are the relevant sections of my code:

HTML (excerpt)

<label for="name">File delimiter (optional, max 1 character):</label>

<input type="text" id="delimiter" name="delimiter" required
minlength="0" maxlength="1" size="1"><br>

JS (excerpt)

async function getRelease(idFiltered) {
  return fetch(`https://api.***.com/releases/${idFiltered}`, {
    headers: {
      'User-Agent': '***/0.1',
      'Authorization': `*** key=${KEY}, secret=${SECRET}`,
    },
  }).then(response => response.json())
    .then(data => {
      if (data.message === 'Release not found.') {
        return { error: `Release with ID ${idFiltered} does not exist` };
      } else {
        const { country = 'Unknown', genres = [], styles = [], year = 'Unknown' } = data;
        const artists = data.artists?.map?.(artist => artist.name);
        const barcode = data.identifiers.filter(id => id.type === 'Barcode').map(barcode => barcode.value);
        const catno = data.labels.map(catno => catno.catno);
        const descriptions = data.formats.map(descriptions => descriptions.descriptions);
        const format = data.formats.map(format => format.name);
        const labels = data.labels.map(label => label.name);
        const qty = data.formats.map(format => format.qty);
        const tracklist = data.tracklist.map(track => track.title);
        const formattedLabels = labels.map(label => label.name);
        const delimiter = document.getElementById("delimiter").value ?? "|";
        const formattedBarcode = barcode.join(delimiter);
        const formattedCatNo = catno.join(delimiter);
        const formattedGenres = genres.join(delimiter);
        const formattedStyles = styles.join(delimiter);
        const formattedTracklist = tracklist.join(delimiter);
        const preformattedDescriptions = descriptions.toString()
          .replace('"', '""').replace(/,/g, ', ');
        const formattedDescriptions = '"'   preformattedDescriptions   '"';
        console.log(data);

        return [idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        ];
      }
    });
}

When I manually input the delimiter | in the text box on my HTML page, I get the correct output back, for instance...

5,Datacide,CD,1,"Album, Limited Edition",,,RI 026|RI026,Germany,1995,Electronic,Abstract|Ambient|Downtempo,,Flashback Signal|Flowerhead|Deep Chair|So Much Light|Sixties Out Of Tune

but when I don't do that, it is missing!

 5,Datacide,CD,1,"Album, Limited Edition",,,RI 026RI026,Germany,1995,Electronic,AbstractAmbientDowntempo,,Flashback SignalFlowerheadDeep ChairSo Much LightSixties Out Of Tune

I guess the missing delimiter is evaluating to neither null nor undefined for some reason, because I read that the nullish coalescing operator only returns the second operand "when the first one evaluates to either null or undefined (but no other falsy values)" source. So this seems to work instead:

    const delimiter = document.getElementById("delimiter").value || "|";

Can anyone tell me why ?? isn't working for me, and is it OK to use || instead? Thanks.

Edit: I tried switching to ||, but I'm finding that the delimiter is only inserted correctly when I serve my app from my local machine, and not when I serve it from GitHub pages. So it seems this issue is specific to GitHub pages.

CodePudding user response:

Your delimiter could be an empty string, which is falsy, but not nullish. That’s why the logical or works. An empty string is logical false, and so are undefined and null. The || operator will return the right-hand value in more cases than the ?? operator.

CodePudding user response:

According to the docs:

The value (of a text input field) may be an empty string ("").

That's why you cannot rely on the nullish coalescing operator, it only works for null and undefined, while the logical || operator will check if the value is falsy, which is also the case for empty string.

  • Related