Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript how to pass variable to second if statement

I have the below code which is an event listener for a chatbot.

The userType value is not being preserved or passed from the first if statement to the second if statement, the value is undefined.

How can I prevent the userType value from being cleared by the second if statement?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

q('handleEvents', function(name, data) {
  var userType;
  if (name === 'QCP') {
    userType = "CP";
    console.log(userType);
  }
  if (name === 'EC') {
    console.log('EC found');
    console.log(userType);
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      'event': 'qlc',
      'qUserType': userType
    });
  }
});

>Solution :

You could put userType outside the function. You could also seal it in a block so it could be visible to the event handler only (like a static function variable), avoid using var in the modern JS, learn about let and const. That way the variable will be preserved between the event listener’s calls.

Also use else if to avoid the second check if the first is true:

{
   let userType;
   q('handleEvents', function(name, data) {
    if (name === 'QCP') {
      userType = "CP";
          console.log(userType);
    } else if (name === 'EC') {
          console.log('EC found');
      console.log(userType);
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ 
               'event': 'qlc',
               'qUserType' : userType
         });      
    }
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading