[ACCEPTED]-php isset() equivalent in javascript-javascript

Accepted answer
Score: 11

isset() makes two checks: first if the variable is 3 defined, and second if it is null.

You will 2 have to check for both the 'undefined' case 1 and the null case, for example:

if (typeof data !== 'undefined' && data !== null)
Score: 5

ECMAScript defines the hasOwnProperty method for checking 5 if an object has a property of a given name:

var foo = {'bar':'bar'}

alert( foo.hasOwnProperty( 'bar' ) ); //true
alert( foo.hasOwnProperty( 'baz' ) ); //false

EDIT: This 4 doesn't fully answer your question

It's possible 3 for a property to be set as undefined

foo.bar = undefined;

alert( foo.hasOwnProperty( 'bar' ) ); //still true

The important 2 question is: What do you need your truth 1 table to be?

In php:

type  | isset() | == true
------+---------+----------
null  | false   | false
false | true    | false
true  | true    | true
""    | true    | false
"a"   | true    | true
0     | true    | false
1     | true    | true

In JS:

type      | isset() | truthy
----------+---------+--------
NaN       | ?       | false
undefined | ?       | false
null      | false   | false
true      | true    | true
false     | true    | false
""        | true    | false
"a"       | true    | true
0         | true    | false
1         | true    | true
Score: 4

I think the best solution is to look in 1 the source code of php.js:

function isset () {
    // !No description available for isset. @php.js developers: Please update the function summary text file.
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/isset
    // +   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 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    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;
}

More Related questions