Background
I’m working with Zapier’s JavaScript code feature and I’m pretty new to coding but have some basic knowledge.
The Issue
I’m getting an error when trying to process date strings from a WooCommerce webhook. Here’s my current code:
var sourceDate = input.OriginalDate;
var position = sourceDate.indexOf(",");
if (position > 0) {
var formatted = sourceDate.substr(position+1);
var formatted = formatted.substr(0,11);
} else {
var formatted = sourceDate.substr(0,10);
}
output = [{processedDate: formatted}];
The problem is that sometimes the OriginalDate field comes through as undefined, which causes this error:
TypeError: Cannot read property ‘indexOf’ of undefined
What I Need Help With
Am I right that this happens because the variable is undefined? What’s the best way to check if the variable has a value before running the indexOf method? I want to make sure my automation doesn’t break when the date field is missing.
Thanks for any help!
yeah, that’s it - your indexOf call is on undefined. just add a check like if (sourceDate && sourceDate.indexOf) { before using indexOf. or simpler, just check if (sourceDate) { and do all your processing in there. this happens often with webhooks cuz fields can be missing.
You’re right - the error happens when OriginalDate is undefined. Just add a null check before using string methods:
var sourceDate = input.OriginalDate;
var formatted;
if (sourceDate && typeof sourceDate === 'string') {
var position = sourceDate.indexOf(",");
if (position > 0) {
formatted = sourceDate.substr(position+1).substr(0,11);
} else {
formatted = sourceDate.substr(0,10);
}
} else {
formatted = 'No date provided';
}
output = [{processedDate: formatted}];
The typeof check gives you extra protection since webhook data can come through as different types. I’ve seen dates arrive as numbers or null values, so this catches those edge cases. WooCommerce webhooks can be inconsistent depending on order status and how they’re configured.
I’ve hit this exact Zapier webhook issue before. The undefined value is definitely the problem, but there’s a cleaner fix than what others suggested. Use optional chaining or a simple truthy check upfront:
var sourceDate = input.OriginalDate || '';
var formatted = '';
if (sourceDate.length > 0) {
var position = sourceDate.indexOf(",");
if (position > 0) {
formatted = sourceDate.substr(position+1, 11);
} else {
formatted = sourceDate.substr(0, 10);
}
} else {
formatted = new Date().toISOString().substr(0, 10);
}
output = [{processedDate: formatted}];
This falls back to an empty string and gives you today’s date when no date exists. Way cleaner than nested conditionals and handles undefined values without breaking your automation.