I'm looking for the javascript equivalent of the php function isset()
. I've tried the method described here at JavaScript isset() equivalent but at firebug, error comes up saying
data.del is undefined //Firebug warning/error
if(typeof data.del[0].node != 'undefined') { // codes in my js file
And in some cases
data is null //Firebug warning/error
if(typeof data.storyLine != 'undefined') { // codes in my js file
The logic seems to work but I'm wondering why is there an error then??
Basically, I want to check whether data.del[0].node
or data.storyLine
isset or not??
PHP provides a function isset that determines if a variable is set; this means if a variable is declared and assigned a value other than null. When a variable is assigned to null, isset() will return false. In JavaScript, we need to determine whether a variable is set or not.
The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
isset() makes two checks: first if the variable is defined, and second if it is null.
You will have to check for both the 'undefined' case and the null case, for example:
if (typeof data !== 'undefined' && data !== null)
ECMAScript defines the hasOwnProperty
method for checking 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 doesn't fully answer your question
It's possible for a property to be set as undefined
foo.bar = undefined;
alert( foo.hasOwnProperty( 'bar' ) ); //still true
The important question is: What do you need your truth 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With