Code-based Actions: Object property is undefined

You can check if the property of an object is undefined using JavaScript. Based on the outcome, you can adjust your flows. Within the bot, you can work with several objects that contain properties. Using these properties, you can adjust your flow. Consider the following example:

Your customer service bot is available as a Web Widget and is active in two places:

  1. While the user logs in.
  2. On your home homepage without the login.

When the chat between the end user and bot requires a handover or takeover, you might want to adjust your flow based on the information that you have from your end user. In the case where the handover is requested during login, you will be able to respond to the end user as the user name and email address is available. When the user enters the handover from the homepage, their profile is undefined and you have to ask for their first name and email address.

The typeof operator

You can use the typeof operator in JavaScript to check the type of an object property. The typeof operator will return a string that contains one of the following:

  • object
  • string
  • number
  • undefined

In the following example, we will adjust our flow based on the user's email address. If the email address of the user exists (e.g. "[email protected]"), the typeof operator will return a string. If the user is anonymous it will return undefined.

If the returned value is a string we can assume that the email address is known. Therefore the bot triggers an event Profile-Known. If the returned value is not a string, it can be an object, number, or undefined. In this case, the bot triggers an event Profile-Unknown. Ensure to create events that match the names in your bot design.

async payload => {  
  // check if a string will be returned  
  if(typeof [payload.user.profile.email][0] === 'string') {
// Trigger an event
trigger('Profile-Known')
} else {  
    // Trigger other event  
    trigger('Profile-Unknown')  
  }  
}