82

Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.

thanks.

4
  • 1
    do you mean null check or dom availability check... Commented Nov 20, 2010 at 8:05
  • what does?? isset does..in php , i don't know thats why i am asking Commented Nov 20, 2010 at 8:07
  • @gov isset — Determine if a variable is set and is not NULL - php.net/manual/en/function.isset.php Commented Nov 20, 2010 at 8:09
  • ok , got a kind of null check Commented Nov 20, 2010 at 8:13

11 Answers 11

165

Try this expression:

typeof(variable) != "undefined" && variable !== null

This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.

You can use it like this:

if(typeof(variable) != "undefined" && variable !== null) {
    bla();
}
Sign up to request clarification or add additional context in comments.

12 Comments

I think you meant && variable !== null.
No, I absolutely meant &&. The variable may be defined and still null. You are correct about the strict type-checking though so I will add that to my answer, thanks.
I briefly tried the second of your alternatives. It did not work out because trying to call the custom isset() fuction with an undefined argument threw an exception in FF4. The first option worked for me. Thanks.
Your function can cause an exception. stackoverflow.com/questions/4231789/…
I don't think "variable !== null belongs" here. variable = null can be a defined value with important meaning. I would push null checks to another "empty" or "hasValue" function instead. Primarily isset is used to prevent non instantiation errors and set defaults, not to check the substance of the variable.
|
11

JavaScript isset() on PHP JS

function isset () {
    // 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;
}

2 Comments

does not work <script> if(!isset(res)){ alert('not set') } alert('go to here') </script>
This solution works for many people. Probably, you've make some mistake. Please, provide more details about your problem e.g. console output or something else.
5

typeof will serve the purpose I think

if(typeof foo != "undefined"){}

1 Comment

Note, however, that typeof null == 'object' - just another one of the quirks of JavaScript.
4

If you want to check if a property exists: hasOwnProperty is the way to go

And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.

1 Comment

Clever, but only useful if you know which object you are working on.
4

Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.

// isset helper function 
var isset = function(variable){
    return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}

Here is a usage example of how to use it:

var example = 'this is an example';
if(isset(example)){
    console.log('the example variable has a value set');
}

It depends on the situation you need it for but let me break down what each part does:

  1. typeof(variable) !== "undefined" checks if the variable is defined at all
  2. variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
  3. variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case

Hope this helps someone :)

Comments

3

Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454

1 Comment

+1. Speed is everything in Js...
3

http://phpjs.org/functions/isset:454

phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.

Comments

2

The problem is that passing an undefined variable to a function causes an error.

This means you have to run typeof before passing it as an argument.

The cleanest way I found to do this is like so:

function isset(v){
    if(v === 'undefined'){
        return false;
    }
    return true;
}

Usage:

if(isset(typeof(varname))){
  alert('is set');
} else {
  alert('not set');
}

Now the code is much more compact and readable.

This will still give an error if you try to call a variable from a non instantiated variable like:

isset(typeof(undefVar.subkey))

thus before trying to run this you need to make sure the object is defined:

undefVar = isset(typeof(undefVar))?undefVar:{};

2 Comments

If you are lazy like me and you are using a proper IDE like netbeans. Just add something like this to your code templates: (abbreviation: isset) isset(typeof(${cursor})) . Small things like this can save you a hell of a lot of time.
Another netbeans shortcut: (abbreviation: set) ${variable} = isset(typeof(${variable}))?${variable}:{};
0

Here :)

function isSet(iVal){
 return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false

2 Comments

You may want to add additional details as to why this will help the OP.
yes, please add some explanation of your code, how it solves the problem, and what the OP was missing or doing wrong. This will help others in the future
0

in addition to @emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").

Comments

-1

You can just:

if(variable||variable===0){
    //Yes it is set
    //do something
}
else {
    //No it is not set
    //Or its null
    //do something else 
}

2 Comments

@user9 if 0 it will go to else because 0 is equal to false
and that can be a non desired behavior and not analog to isset

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.