I’m working on a Zapier automation where I need to parse URL parameters and set fallback values when they’re missing. I have this working code that extracts marketing tracking parameters from URLs:
let pageURL = inputData.URL;
let paramString = pageURL.split("?")[1];
let params = new URLSearchParams(paramString);
let source = params.get('utm_source');
let campaign = params.get('utm_campaign');
let medium = params.get('utm_medium');
let term = params.get('utm_term');
let content = params.get('utm_content');
output = [{pageURL, paramString, source, campaign, medium, term, content}];
The issue is when URLs don’t have these parameters, they return null values. I want to set a default value like “direct” when they’re missing. I tried this approach but it’s not working:
if(campaign === null || typeof campaign === "undefined" || campaign === "") {
campaign = "DIRECT";
}
What’s the correct way to handle this in JavaScript? Any help would be great!
you can also use the nullish coalescing operator (??) - it only triggers on null/undefined, not empty strings. so let source = params.get('utm_source') ?? 'direct' works great. just make sure your url actually has a query string before splitting, since pageURL.split("?")[1] will break if there’s no ? in the url.
Your code’s gonna crash if there’s no query string at all. The real issue is that pageURL.split("?")[1] returns undefined when there’s no ? in the URL.
Fix it like this: let paramString = pageURL.includes('?') ? pageURL.split('?')[1] : ''; then create your URLSearchParams from that.
Your if statement logic is fine, but I’d also check for whitespace: if(!campaign || campaign.trim() === '') { campaign = 'DIRECT'; }. This gives you way more control over empty values than just using || or ??.
To handle default values for missing URL parameters, you can utilize the logical OR operator (||). This approach allows for a concise way to set default values directly when extracting parameters. For instance:
let source = params.get('utm_source') || 'direct';
let campaign = params.get('utm_campaign') || 'direct';
let medium = params.get('utm_medium') || 'direct';
let term = params.get('utm_term') || 'direct';
let content = params.get('utm_content') || 'direct';
This method reduces complexity compared to using multiple if statements. The || operator automatically provides the default value if the parameter is null or any falsy value.