PHP isset() equiv JavaScript isset() funciton:
Often I am get asked from junior developers that, Is there any isset() function in Javascript? Ha ha ha. I ignore them, but let them try to create a custom function to do this job.Ok no more words...Let get it...
/** * * @returns {Boolean} * Original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) * Improved by: FremyCompany * Improved by: Onno Marsman * Improved by: RafaĆ Kukawski * Example-1: isset( undefined, true); * Returns: false * Example 2: isset( 'Kevin van Zonneveld' ); * Returns: true */ function isset () { var a = arguments, l = a.length, i = 0, undef; if (l === 0) { throw new Error('Empty isset'); } while (i !== l) { if (a[i] === undef || a[i] === null) { return false; } i++; } return true; }
But........
The problem is this will raise an exception when calling
The problem is this will raise an exception when calling
isset(abc.def.ghi)
in case if abc.def
is undefined. However by combining this solution with the one that accepts a variable name in a form of a string, it will be identical to the PHP version
You can use this function as PHP isset() given to use.
var a; a = { b: { c: 'e' } }; function isset (obj, path) { var stone; path = path || ''; if (path.indexOf('[') !== -1) { throw new Error('Unsupported object path notation.'); } path = path.split('.'); do { if (obj === undefined) { return false; } stone = path.shift(); if (!obj.hasOwnProperty(stone)) { return false; } obj = obj[stone]; } while (path.length); return true; } console.log( isset(a, 'b') == true, isset(a, 'b.c') == true, isset(a, 'b.c.d') == false, isset(a, 'b.c.d.e') == false, isset(a, 'b.c.d.e.f') == false );
Another Way to do isset() function using javascript.
if(typeof(data.length) != 'undefined') { // do something } if(empty(data)) { // do something } if(typeof(data) == 'undefined' || data === null) { //do something }
JavaScript isset() equivalent PHP isset()
By Game Changer →
Thursday, December 17, 2015