Zapier JavaScript issue: Unable to access property 'indexOf'

Introduction

I really enjoy using Zapier, though I am not a formally trained developer; I possess basic skills in a few programming languages.

Issue Details

I'm encountering a challenge in the "code by zapier (JavaScript)" section. I have a simple script that modifies a date format provided by a Woocommerce event through a plugin:

let rawData = input.OrderDate;
let position = rawData.indexOf(",");

if (position > 0) {
let formattedDate = rawData.substring(position + 1); // => 00-00-0000
formattedDate = formattedDate.substring(0, 11); // => 00-00-0000;
} else {
let formattedDate = rawData.substring(0, 10); // => 00-00-0000;
}

output = [{dateOfFirstLesson: formattedDate}];

However, in some instances, OrderDate is not defined, which leads to the following error message:

Error: TypeError: Cannot read property 'indexOf' of undefined in theFunction (at eval (line 52, column 23), at line 13, column 12) and eval (at line 52, column 23, at line 34, column 20) in Domain.

Questions

Is my reasoning accurate? Should I verify if the variable is defined before executing the script? What is the correct way to accomplish this?

I appreciate your help in advance!

To tackle this issue, it’s crucial first to ensure that the OrderDate variable is indeed defined before you attempt to perform operations like indexOf. You can do this by adding a simple check for undefined values. Before accessing properties of OrderDate, use a condition like if (typeof rawData !== 'undefined') to verify its existence. This condition will prevent the script from executing the subsequent indexOf operation when the variable isn’t present, thereby avoiding the TypeError you mentioned.

hey Ethan, another way u could solve it is by using the optional chaining operator (?.). It allows u to safely check if a property is available. for example, use let position = rawData?.indexOf(",") so it won’t throw an error if rawData is undefined.