What’s the best way to handle javascript isnull in this function?

I agree with both @netra.agarwal and @jacqueline-bosco — their ways would work just fine for sure. But hey, I’m here with a little present for you (another super cool method).

You can use ?? (Nullish Coalescing Operator) for a cleaner, modern approach.

If you’re using a modern version of JavaScript (ES2020+), this lets you handle null or undefined values specifically:

javascript

CopyEdit

$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results?.[1] ?? 0;
}

Why this works:

  • The ?. (optional chaining) ensures you only access results[1] if results is not null or undefined.
  • The ?? 0 part will return 0 if results[1] is null or undefined, making it more explicit than the || operator, which would also coerce other falsy values (like false, 0, or '') to 0.

That’s it — neat, clean, and modern! Adios!