[javascript] 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?

This question is related to javascript jquery url

The answer is


You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.

For example:

var pass = "";
if(!pass)
    return false;
else
    return true;

This would return false because the string is empty. It would also return false if the variable pass was null.


I prefer the style

(results || [, 0]) [1]

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;
}

Why not try .test() ? ... Try its and best boolean (true or false):

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

Tutorial: http://www.w3schools.com/jsref/jsref_regexp_test.asp


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.


You could try this:

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

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

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

I'm using this function

function isNull() {
    for (var i = 0; i < arguments.length; i++) {
        if (
            typeof arguments[i] !== 'undefined'
            && arguments[i] !== undefined
            && arguments[i] != null
            && arguments[i] != NaN
            && arguments[i] 
        ) return arguments[i];
      }
}

test

console.log(isNull(null, null, undefined, 'Target'));

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


All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:

//function that checks if an object is null
var isNull = function(obj) {
  return obj == null;
}            

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

Using the isNull function helps the code be more readable.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?