I’m using this jQuery snippet to get URL parameters:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
But I want to add an isnull JavaScript check so it returns 0 if the parameter doesn’t exist (i.e., results is null).
The usual if (results == null) { … } feels clunky.
Is there a cleaner way?
You can simplify with modern JS using optional chaining (?.) and nullish coalescing (??):
return results?.[1] ?? 0;
This means if results or results[1] is null or undefined, return 0. Clean, concise, and easy to understand!
@Shreshthaseth If you want to keep it ES5-compatible, a ternary operator makes it less bulky:
return results ? results[1] : 0;
This does the null check inline without multiple lines, keeping your function tidy.
Another elegant approach is using logical AND (&&) to guard the access:
return (results && results[1]) || 0;
It returns results[1] if results exists, otherwise 0.
This is a common idiom familiar to many JavaScript developers.