Javascript variable checking: (null or undefined) vs boolean - javascript

I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).
Is there an easy way in JS or Underscore to check this without doing
(obj.x != null || obj.x != undefined)
???

You could use just the standard typeof operator, which returns 'boolean' if boolean.
console.log(typeof undefined === 'boolean'); // false
console.log(typeof null === 'boolean'); // false
console.log(typeof true === 'boolean'); // true
console.log(typeof false === 'boolean'); // true

The typeof operator can return whether it is boolean or anything else
Reference here

I found an easy way in Underscore:
_.isBoolean(obj.x)
Thanks to Rajesh I know now that obj.x != null returns the same if x is null or undefined.
I prefer the Underscore function because it's readable, but the null comparison is native JS and seems more efficient, and simpler.

Try this Hope it will help you,
JavaScript
function test(v) {
let type = typeof v;
if(type === 'undefined') {
return true;
}
if(type=== 'boolean') {
return false;
}
if(v === null) {
return true;
}
if(v === undefined) {
return true;
}
if(v instanceof Array) {
if(v.length < 1) {
return true;
}
}
else if(type === 'string') {
if(v.length < 1) {
return true;
}
}
else if(type === 'object') {
if(Object.keys(v).length < 1) {
return true;
}
}
else if(type === 'number') {
if(isNaN(v)) {
return true;
}
}
return false;
}

In Javascript, undefined is evaluated as false, so you should be able to do
if (obj.x) {
// ...
}

Related

How to refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed

How to refactor this function to reduce the complexicity
When I am using switch case at that time code complixity is more so how to reduce it
How to achive this
var has = Object.prototype.hasOwnProperty
var toString = Object.prototype.toString
function isEmpty(val) {
if (val == null) return true
if ('boolean' == typeof val) return false
if ('number' == typeof val) return val === 0
if ('string' == typeof val) return val.length === 0
if ('function' == typeof val) return val.length === 0
if (Array.isArray(val)) return val.length === 0
if (val instanceof Error) return val.message === ''
if (val.toString == toString) {
switch (val.toString()) {
case '[object File]':
case '[object Map]':
case '[object Set]': {
return val.size === 0
}
case '[object Object]': {
for (var key in val) {
if (has.call(val, key)) return false
}
return true
}
}
}
return false
}
module.exports = isEmpty
I recently gave an answer to a very similar question going a little more into detail about how cognitive complexity works (see https://stackoverflow.com/a/62867219/7730554).
But in general, I think it is important to understand that cognitive complexity is increased even more if there are nested conditions. This calculation is done this way because the human brain can deal a lot better with statements written in sequence rather than with nested conditions. So for each conditional statement (if, switch, for loop, etc.) there will be a +1 added to the complexity value. But for each nested condition another +1 is added on top of the last level. That means, an if inside an if will not only add +1, but +2. An if, inside an if, inside an if will than result in +1 for the first if, +2 for the second and +3 for the third if condition. If you want to dig deeper into this I recommend taking a look at: https://www.sonarsource.com/docs/CognitiveComplexity.pdf
So let's analyze where the high complexity values from your method originate first:
function isEmpty(val) {
if (val == null) return true // +1
if ('boolean' == typeof val) return false // +1
if ('number' == typeof val) return val === 0 // +1
if ('string' == typeof val) return val.length === 0 // +1
if ('function' == typeof val) return val.length === 0 // +1
if (Array.isArray(val)) return val.length === 0 // +1
if (val instanceof Error) return val.message === '' // +1
if (val.toString == toString) { // +1
switch (val.toString()) { // +2
case '[object File]':
case '[object Map]':
case '[object Set]': {
return val.size === 0
}
case '[object Object]': {
for (var key in val) { // +3
if (has.call(val, key)) return false // +4
}
return true
}
}
}
return false
}
If you look at the comments I added you can easily see where the most problematic code concerning cyclomatic complexity is located. This also relates to the human readabilty of the code.
So one simply step to increase readability and at the same time reduce congnitive complexity is to look for options of "early returns".
To illustrate this, I simply inverted the statement *if (val.toString == toString)" to immediately return false if *val.toString != toString":
function isEmpty(val) {
if (val == null) return true // +1
if ('boolean' == typeof val) return false // +1
if ('number' == typeof val) return val === 0 // +1
if ('string' == typeof val) return val.length === 0 // +1
if ('function' == typeof val) return val.length === 0 // +1
if (Array.isArray(val)) return val.length === 0 // +1
if (val instanceof Error) return val.message === '' // +1
if (val.toString != toString) { // +1
return false;
}
switch (val.toString()) { // +1
case '[object File]':
case '[object Map]':
case '[object Set]': {
return val.size === 0
}
case '[object Object]': {
for (var key in val) { // +2
if (has.call(val, key)) return false // +3
}
return true
}
}
}
Now the last switch statement can be executed outside the if statement and we reduced the nesting level by one. With that simple change the cognitive complexity has now dropped to 14 instead of 17.
You could then even go a step further and change the last case statement by extracting the return value into a variable and either extract a separate method out of the code block. This would reduce the complexity of the isEmpty() method even more.
And besides from extracting a method you can also use a declarative approach and use, for instance the Array method find() which would reduce the cognitive complexity even more.
To illustrate the idea I did both:
function isEmpty(val) {
if (val == null) return true // +1
if ('boolean' == typeof val) return false // +1
if ('number' == typeof val) return val === 0 // +1
if ('string' == typeof val) return val.length === 0 // +1
if ('function' == typeof val) return val.length === 0 // +1
if (Array.isArray(val)) return val.length === 0 // +1
if (val instanceof Error) return val.message === '' // +1
if (val.toString != toString) { // +1
return false;
}
return checkForComplexTypes(val)
}
function checkForComplexTypes(val) {
var result = null
switch (val.toString()) { // +1
case '[object File]':
case '[object Map]':
case '[object Set]': {
result = val.size === 0
}
case '[object Object]': {
result = Object.keys(val).find(key => has.call(val, key))
}
return result
}
}
This should bring down the cognitive complexity of the isEmpty() method to 8 and the whole code including the extracted checkForComplexTypes() function to a complexity score of 9.
Note: JavaScript is not my major language at the moment so I cannot fully guarantee the correctness of the last refactoring step.
If you cannot split the function or use OOP approach, you can use array of functions and iterate over it:
const has = Object.prototype.hasOwnProperty;
const toString = Object.prototype.toString;
function isEmpty(val) {
let isEmpty = null;
const checkFunctions = [
(val) => 'boolean' === typeof val ? false : null,
(val) => 'number' === typeof val ? val === 0 : null,
(val) => ['string', 'function'].includes(typeof val) ? val.length === 0 : null,
(val) => Array.isArray(val) ? val.length === 0 : null,
(val) => val instanceof Error ? val.message === '' : null,
(val) => val.toString == toString && ['[object File]', '[object Map]', '[object Set]'].includes(val.toString()) ? val.size === 0 : null,
(val) => {
if (val.toString == toString && val.toString() === '[object Object]') {
for (var key in val) {
if (has.call(val, key)) return false
}
return true;
}
}
];
for (let i = 0; i < checkFunctions.length; i++) {
isEmpty = checkFunctions[i](val);
if (isEmpty !== null) {
return isEmpty;
};
}
}
console.log(isEmpty(''), true);
console.log(isEmpty('Hallo'), false);
console.log(isEmpty(0), true);
console.log(isEmpty(1), false);
console.log(isEmpty({}), true);
console.log(isEmpty({a: 1}), false);
You can also extend core types of JS and then instead of isEmpty(val) write val.isEmpty(). For example:
String.prototype.isEmpty = function() {return this.length === 0}
Array.prototype.isEmpty = function() {return this.length === 0}
console.log("".isEmpty(), true);
console.log("foo".isEmpty(), false);
console.log([].isEmpty(), true);
console.log([1,2,3].isEmpty(), false);

How Set local storage to 0 if undefined?

if localStorage["BestScore"] = undefined;
{
localStorage["BestScore"]=0;
maxScore=0;
}
var maxScore=localStorage["BestScore"];
var newScore=false
function drawScore(score) {
if (newScore == true && score < maxScore) {
newScore = false;
}
if (score > maxScore) {
newScore = true;
localStorage["BestScore"] = score;
if ([5, 10, 15, 20].indexOf(score) !== -1) {
play(sndMedal);
} else {
play(sndGain);
}
}
This code is to set the max score and then store it but it doesn't seem to set the local storage to 0 if undefined.
if localStorage["BestScore"] = undefined;
should be:
if( typeof localStorage["BestScore"] === 'undefined' )
However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:
if (typeof localStorage["BestScore"] === "undefined") {
localStorage["BestScore"] = 0;
}
It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.
if localStorage["BestScore"] = undefined;
should be ==
else you are assigning, not comparing.
use == or === as a comparison operator, then it should be fine

JavaScript: Check to see if a variable or object exists

I have a function to return if a variable/object is set or not:
function isset() {
var a = arguments, l = a.length;
if (l === 0) { console.log("Error: isset() is empty"); }
for (var i=0; i<l; i++) {
try {
if (typeof a[i] === "object") {
var j=0;
for (var obj in a[i]) { j++; }
if (j>0) { return true; }
else { return false; }
}
else if (a[i] === undefined || a[i] === null) { return false; }
}
catch(e) {
if (e.name === "ReferenceError") { return false; }
}
}
return true;
}
For example, this works:
var foo;
isset(foo); // Returns false
foo = "bar";
isset(foo); // Returns true
foo = {};
isset(foo); // Returns false
isset(foo.bar); // Returns false
foo = { bar: "test" };
isset(foo); // Returns true
isset(foo.bar); // Returns true
Here is the problem... if foo is never set to begin with, this happens:
// foo has not been defined yet
isset(foo); // Returns "ReferenceError: foo is not defined"
I thought I could use try/catch/finally to return false if error.name === "ReferenceError" but it isn't working. Where am I going wrong?
Edit:
So the answer below is correct. As I expected, you cannot access an undefined variable or trap it with try/catch/finally (see below for an explanation).
However, here is a not so elegant solution. You have to pass the name of the variable in quotes, then use eval to do the checking. It's ugly, but it works:
// Usage: isset("foo"); // Returns true or false
function isset(a) {
if (a) {
if (eval("!!window."+a)) {
if (eval("typeof "+a+" === 'object'")) { return eval("Object.keys("+a+").length > 0") ? true : false; }
return (eval(a+" === undefined") || eval(a+" === null") || eval(a+" === ''")) ? false : true;
}
else { return false; }
}
else { console.log("Empty value: isset()"); }
}
And just to follow up some more, I cleaned up the original function at the very top. It still has the same problem where if the variable doesn't exist you get a ReferenceError, but this version is much cleaner:
// Usage: isset(foo); // Returns true or false if the variable exists.
function isset(a) {
if (a) {
if (typeof a === "object") { return Object.keys(a).length > 0 ? true : false; }
return (a === undefined || a === null || a === "") ? false : true;
}
else { console.log("Empty value: isset()"); }
}
You just can't do that type of check with a function. In order to pass the variable, it needs to exist, so it will fail before your code can run.
When you call it on the undeclared variable, you're attempting to resolve the value of the identifier in the argument position.
// v----resolve identifier so it can be passed, but resolution fails
isset(foo);
And of course, it doesn't exist, so the ReferenceError is thrown.
JavaScript doesn't have pointers, so there's nothing like a nil pointer that can be passed in its place.
You cannot pass a identifier that hasn't been initialised. You could pass a string, and an object to test, like the following:
function isset(str, obj) {
return obj[str] ? true : false;
}
isset("foo", window); // >>> false

Checking something isEmpty in Javascript?

How can I check if a variable is empty in Javascript?
if(response.photo) is empty {
do something
else {
do something else
}
response.photo was from JSON, and it could be empty sometimes, empty data cells! I want to check if it's empty.
If you're testing for an empty string:
if(myVar === ''){ // do stuff };
If you're checking for a variable that has been declared, but not defined:
if(myVar === null){ // do stuff };
If you're checking for a variable that may not be defined:
if(myVar === undefined){ // do stuff };
If you're checking both i.e, either variable is null or undefined:
if(myVar == null){ // do stuff };
This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.
// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x)
// test for null OR undefined
if (x == null)
// test for undefined OR null
if (x == undefined)
// test for undefined
if (x === undefined)
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined')
// test for empty string
if (x === '')
// if you know its an array
if (x.length == 0)
// or
if (!x.length)
// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
empty = false;
break;
}
This should cover all cases:
function empty( val ) {
// test results
//---------------
// [] true, empty array
// {} true, empty object
// null true
// undefined true
// "" true, empty string
// '' true, empty string
// 0 false, number
// true false, boolean
// false false, boolean
// Date false
// function false
if (val === undefined)
return true;
if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
return false;
if (val == null || val.length === 0) // null or 0 length array
return true;
if (typeof (val) == "object") {
// empty object
var r = true;
for (var f in val)
r = false;
return r;
}
return false;
}
I see potential shortcomings in many solutions posted above, so I decided to compile my own.
Note: it uses Array.prototype.some, check your browser support.
Solution below considers variable empty if one of the following is true:
JS thinks that variable is equal to false, which already covers many things like 0, "", [], and even [""] and [0]
Value is null or it's type is 'undefined'
It is an empty Object
It is an Object/Array consisting only of values that are empty themselves (i.e. broken down to primitives each part of it equals false). Checks drill recursively into Object/Array structure.
E.g.
isEmpty({"": 0}) // true
isEmpty({"": 1}) // false
isEmpty([{}, {}]) // true
isEmpty(["", 0, {0: false}]) //true
Function code:
/**
* Checks if value is empty. Deep-checks arrays and objects
* Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
* #param value
* #returns {boolean}
*/
function isEmpty(value){
var isEmptyObject = function(a) {
if (typeof a.length === 'undefined') { // it's an Object, not an Array
var hasNonempty = Object.keys(a).some(function nonEmpty(element){
return !isEmpty(a[element]);
});
return hasNonempty ? false : isEmptyObject(Object.keys(a));
}
return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
return !isEmpty(element); // at least one element should be non-empty
});
};
return (
value == false
|| typeof value === 'undefined'
|| value == null
|| (typeof value === 'object' && isEmptyObject(value))
);
}
Here my simplest solution.
Inspired by PHP empty function
function empty(n){
return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);
}
//with number
console.log(empty(0)); //true
console.log(empty(10)); //false
//with object
console.log(empty({})); //true
console.log(empty({a:'a'})); //false
//with array
console.log(empty([])); //true
console.log(empty([1,2])); //false
//with string
console.log(empty('')); //true
console.log(empty('a')); //false
A more readable version of #SJ00 answer:
/**
* Checks if a JavaScript value is empty
* #example
* isEmpty(null); // true
* isEmpty(undefined); // true
* isEmpty(''); // true
* isEmpty([]); // true
* isEmpty({}); // true
* #param {any} value - item to test
* #returns {boolean} true if empty, otherwise false
*/
function isEmpty(value) {
return (
value === null || // check for null
value === undefined || // check for undefined
value === '' || // check for empty string
(Array.isArray(value) && value.length === 0) || // check for empty array
(typeof value === 'object' && Object.keys(value).length === 0) // check for empty object
);
}
See http://underscorejs.org/#isEmpty
isEmpty_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.
Combining answers from #inkednm into one function:
function isEmpty(property) {
return (property === null || property === "" || typeof property === "undefined");
}
Empty check on a JSON's key depends on use-case. For a common use-case, we can test for following:
Not null
Not undefined
Not an empty String ''
Not an empty Object {} [] (Array is an Object)
Function:
function isEmpty(arg){
return (
arg == null || // Check for null or undefined
arg.length === 0 || // Check for empty String (Bonus check for empty Array)
(typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
);
}
Return true for:
isEmpty(''); // Empty String
isEmpty(null); // null
isEmpty(); // undefined
isEmpty({}); // Empty Object
isEmpty([]); // Empty Array
just put the variable inside the if condition, if variable has any value it will return true else false.
if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
alert("Has Value");
}
else
{
alert("No Value");
};
What about doing like this.
JSON.stringify({}) === "{}"
just be careful with all what i see here:
typeof object === 'object' && Object.keys(object).length === 0) is indeed checking if an object is Empty. But did you know that Date in javascript are considered object also?
so if you do:
const shouldNotbeEmpty = new Date(Date.now())
isEmpty(shouldNotbeEmpty) // this will return true when it should not
my only way to figure it out to fix that was to check if the object is a Date instance:
typeof value === "object" && Object.keys(value).length === 0 && !value instanceof Date
so something like this:
const isObject = value => typeof value === "object" && Object.keys(value).length === 0
const isString = value => typeof value === "string" && value.trim().length === 0
const isEmpty = value => {
const isDate = value instanceof Date
return value === undefined || value === null || (isObject(value) && !isDate) || isString(value)
}
exports.isEmpty = isEmpty
const isEmpty = value => {
if (!value && value !== 0) return true
if(Array.isArray(value)){
if(!value.length) return true
return value.every(isEmpty)
}
if (typeof value === 'object') {
return Object.values(value).every(isEmpty)
}
return false
}
isEmpty(); // true
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(0); // false
isEmpty(1); // false
isEmpty(''); // true
isEmpty('a'); // false
isEmpty([]); // true
isEmpty([0]); // false
isEmpty([1]); // false
isEmpty([[]]); // true
isEmpty([[], []]); // true
isEmpty([[], null, undefined]); // true
isEmpty([[], 1]); // false
isEmpty({}); // true
isEmpty({a: 1}); // false
isEmpty({a: 1, b: 2}); // false
isEmpty({a: 1, b: {}}); // false
isEmpty({a: null, b: [], c: undefined}); // true
isEmpty({a: {}, b: {}, c: {}}); // true
isEmpty(() => {}) // false
It depends on what you mean by "empty". The most common pattern is to check to see if the variable is undefined. Many people also do a null check, for example:
if (myVariable === undefined || myVariable === null)...
or, in a shorter form:
if (myVariable || myVariable === null)...
if (myVar == undefined)
will work to see if the var is declared but not initalized.
Check for undefined:
if (typeof response.photo == "undefined")
{
// do something
}
This would do the equivelant of vb's IsEmpty. If myvar contains any value, even null, empty string, or 0, it is not "empty".
To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator.
if ("photo" in response)
{
// do something
}
If you're looking for the equivalent of PHP's empty function, check this out:
function empty(mixed_var) {
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty({'aFunc' : function () { alert('humpty'); } });
// returns 5: false
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixed_var === emptyValues[i]) {
return true;
}
}
if (typeof mixed_var === 'object') {
for (key in mixed_var) {
// TODO: should we check for own properties only?
//if (mixed_var.hasOwnProperty(key)) {
return false;
//}
}
return true;
}
return false;
}
http://phpjs.org/functions/empty:392
what am I missing if empty array... keyless object... falseness
const isEmpty = o => Array.isArray(o) && !o.join('').length || typeof o === 'object' && !Object.keys(o).length || !(+value);
Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).
function empty(mixed_var) {
if (!mixed_var || mixed_var == '0') {
return true;
}
if (typeof mixed_var == 'object') {
for (var k in mixed_var) {
return false;
}
return true;
}
return false;
}
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty(0);
// returns 5: true
// example 6: empty('0');
// returns 6: true
// example 7: empty(function(){});
// returns 7: false
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
function isEmpty(variable) {
const type = typeof variable
if (variable === null) return true
if (type === 'undefined') return true
if (type === 'boolean') return false
if (type === 'string') return !variable
if (type === 'number') return false
if (Array.isArray(variable)) return !variable.length
if (type === 'object') return !Object.keys(variable).length
return !variable
}
My solution:
function isEmpty(object) {
return (
(!object)
|| (object === undefined)
|| (object === null)
|| (object === '')
|| ((object?.length !== undefined) && (object.length === 0))
|| (typeof object === 'object' && Object.keys(object).length === 0)
);
}
Tests with Jest:
describe('isEmpty should return `false` when the parameter have some truthy value.', () => {
test('Empty objects should return true', () => {
expect(utils.isEmpty([])).toBe(true);
expect(utils.isEmpty({})).toBe(true);
expect(utils.isEmpty('')).toBe(true);
expect(utils.isEmpty(undefined)).toBe(true);
expect(utils.isEmpty(null)).toBe(true);
});
test('Truthy objects should return false', () => {
expect(utils.isEmpty([1])).toBe(false);
expect(utils.isEmpty({a: undefined})).toBe(false);
expect(utils.isEmpty({a: 5})).toBe(false);
expect(utils.isEmpty({a: 5, b: 6, c: undefined})).toBe(false);
expect(utils.isEmpty('f00')).toBe(false);
expect(utils.isEmpty('0')).toBe(false);
});
})
var message_1 = message.trim();
if (message_1.length > 0) {
// to do
}

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?
return results == null ? 0 : (results[1] || 0);
return results == null ? 0 : ( results[1] || 0 );
the 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 );
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.
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]
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
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.

Categories

Resources