81

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.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
gautamlakum
  • 11,815
  • 23
  • 67
  • 90

11 Answers11

164

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();
}
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • I think you meant `&& variable !== null`. – PleaseStand Nov 20 '10 at 08:12
  • 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. – Emil Vikström Nov 20 '10 at 08:15
  • 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. – C.O. Jun 08 '11 at 15:04
  • Your function can cause an exception. http://stackoverflow.com/questions/4231789/is-ther-something-like-isset-of-php-in-javascript-jquery/10138008#10138008 – Oleg Apr 13 '12 at 09:00
  • Oleg, yes, someone else have already mentioned that. I've removed the function. – Emil Vikström Apr 13 '12 at 09:01
  • You could just improve your function. Look at my answer ;) http://stackoverflow.com/questions/4231789/is-ther-something-like-isset-of-php-in-javascript-jquery/10138008#10138008 – Oleg Apr 13 '12 at 09:02
  • Yes, but I thought that was irrelevant since someone else already mentioned PHPJS. – Emil Vikström Apr 13 '12 at 09:02
  • 2
    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. – Dieter Gribnitz Dec 19 '13 at 08:48
  • user787301, the PHP [isset](http://php.net/isset) function does a NULL check. I also prefer to treat NULL as "not set" since that is the meaning in most languages; and if I may add even more personal opinions I think that you should know whether your variable is defined or not before trying to read it (in which case the NULL check is the *only* correct part of my answer). You are correct that NULL carries a meaning: the meaning of a value that is not set; a value without a value. – Emil Vikström Dec 19 '13 at 10:16
  • what do you think about the rocking (!!) double not operator guys? – Haseeb Zulfiqar Jul 25 '16 at 11:00
  • Yeah it is more robust and concise enough – Faris Rayhan Apr 13 '18 at 07:20
  • this is weird, when using with this.value it doesn't work.. like if(typeof(this.value) != "undefined" && this.value !== null) does not detect undefined this.value properties – Robert Sinclair May 09 '20 at 03:10
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;
}
Oleg
  • 7,070
  • 4
  • 47
  • 49
  • does not work – dazzafact Sep 23 '14 at 14:35
  • 1
    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. – Oleg Sep 23 '14 at 19:36
5

typeof will serve the purpose I think

if(typeof foo != "undefined"){}
DanneManne
  • 21,107
  • 5
  • 57
  • 58
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 :)

stuyam
  • 9,561
  • 2
  • 21
  • 40
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.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
3

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

Ioannis Karadimas
  • 7,746
  • 3
  • 35
  • 45
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.

Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144
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:{};
Dieter Gribnitz
  • 5,062
  • 2
  • 41
  • 38
  • 1
    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. – Dieter Gribnitz Dec 19 '13 at 08:31
  • 1
    Another netbeans shortcut: (abbreviation: set) ${variable} = isset(typeof(${variable}))?${variable}:{}; – Dieter Gribnitz Dec 19 '13 at 09:27
0

Here :)

function isSet(iVal){
 return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
  • 3
    You may want to add additional details as to why this will help the OP. – Zane Apr 21 '14 at 17:49
  • 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 – Our Man in Bananas Apr 21 '14 at 20:33
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").

-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 
}
a1204773
  • 6,923
  • 20
  • 64
  • 94