Home > Net >  Ternary operator - when variable is undefined
Ternary operator - when variable is undefined

Time:06-04

I have a fn that creates and populate variable linkedinInsight when its invoked.

Just a quick overview of this fn, it will check the response data and see if there is a match. If yes, it would populate the linkedinInight variable with the data.

Using Ternary operation, I am unable to display "undefined" when the variable is undefined. linkedinInsight === undefined ? "undefined" : "Variable exist"

However, if the fn gets a match, I could see "Variable exist" displayed.

In the case where variable is undefined, from the console, it is showing

Error handling response: TypeError: Cannot read properties of undefined (reading 'insight_tags')
    at chrome-extension://fpncfpgjnkfnlafmojhhpgophpgikaao/popup.js:13:60

The objective here is to present the data and if we couldnt find data, I would like to return a "Data not found message".

Any help guys?

document.addEventListener(
  "DOMContentLoaded",
  function () {
    var checkPageButton = document.getElementById("clickIt");
    checkPageButton.addEventListener(
      "click",
      function () {
        chrome.tabs.getSelected(null, function (tab) {
          const backgroundPage = chrome.extension.getBackgroundPage();

          const linkedinInsight =
            backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags;


          alert(
            linkedinInsight === undefined ? "undefined" : "Variable exist"
          );

CodePudding user response:

The issue is in below line, replace

const linkedinInsight =
            backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags;

with

const linkedinInsight =
            (backgroundPage && backgroundPage["_linkedin_pixel_data"] && backgroundPage["_linkedin_pixel_data"][tab.id] && backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags) || undefined;

Or if optional chaining is supported

const linkedinInsight =
                backgroundPage?.["_linkedin_pixel_data"]?.[tab.id]?.insight_tags;

CodePudding user response:

Use a nullish coalescingm operator

let exists = value ?? `${value} doesn't exist`;

If the value is undefined or null then return the value on the right side of operator ??

function check(X) {
  let present = X  ?? `"X" does not exist`;
  let limit = X < 10 && X > 0 ? `"X" is within range` :  `"X" is out of range`;
  if (typeof present == 'string') {
    console.log(present);
    return;
  }
  console.log(limit);
}

check(5);
check(10);
check(-1);
check();
check(null);

  • Related