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 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?
212 Answers
return results == null ? 0 : (results[1] || 0); 3return results == null ? 0 : ( results[1] || 0 ); 3the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.
You could try this:
if(typeof(results) == "undefined") { return 0; } else { return results[1] || 0; } return results==null ? 0 : ( results[1] || 0 ); 1return (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.
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; } 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.
I prefer the style
(results || [, 0]) [1] 3Why 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); } 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')); 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.