views:

108

answers:

7
+2  Q: 

Javascript isnull

This is a really great function written in jQuery to determine the value of a url field:

  $.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
  }
  // example.com?someparam=name&otherparam=8&id=6
  $.urlParam('someparam'); // name
  $.urlParam('id'); // 6
  $.urlParam('notavar'); // null

http://snipplr.com/view/11583/retrieve-url-params-with-jquery/

I would like to add a condition to test for null, but this looks kind of klunky:

 if (results == null) {
  return 0;
 } else {
  return results[1] || 0;
 }

Q: What's the elegant way to accomplish the above if/then statement?

+3  A: 

return results == null ? 0 : ( results[1] || 0 );

Rich
not true: the || deals with the value at results[1]
frunsi
@DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties
just somebody
Well, it looks like you answered first, so you're getting my upvote.
Robert Harvey
removing my downvote: I misunderstood.
DDaviesBrackett
On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0
Rich
A: 
if (typeof(results)!='undefined'){ 
    return results[1];
} else { 
    return 0; 
};

But you might want to check if results is an array. Arrays are of type Object so you will need this function

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

So your code becomes

if (typeOf(results)==='array'){
      return results[1];
}
else
{
      return 0;
}
pixeline
+2  A: 

return results == null ? 0 : (results[1] || 0);

Brad
+1  A: 
return results==null ? 0 : ( results[1] || 0 );
frunsi
+1  A: 

you could try

if(typeof(results )=="undefined"){ return 0; } else { return results[1] || 0; }

streetparade
A: 

the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.

DDaviesBrackett
I'm getting an error "results is null" in firebug if I return results[1] || 0
cf_PhillipSenn
cf_PhillipSenn
A: 
return (results||0) && results[1] || 0;

The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.

Teun D