is there something like isset of php in javascript/jQuery? [duplicate]
Asked Answered
M

11

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.

Marja answered 20/11, 2010 at 8:1 Comment(4)
do you mean null check or dom availability check...Dupaix
what does?? isset does..in php , i don't know thats why i am askingDupaix
@gov isset — Determine if a variable is set and is not NULL - php.net/manual/en/function.isset.phpPeroxidase
ok , got a kind of null checkDupaix
M
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();
}
Misleading answered 20/11, 2010 at 8:7 Comment(12)
I think you meant && variable !== null.Phosphate
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.Estheresthesia
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.Helga
Your function can cause an exception. #4232289Expense
Oleg, yes, someone else have already mentioned that. I've removed the function.Estheresthesia
You could just improve your function. Look at my answer ;) #4232289Expense
Yes, but I thought that was irrelevant since someone else already mentioned PHPJS.Estheresthesia
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.Titular
user787301, the PHP 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.Estheresthesia
what do you think about the rocking (!!) double not operator guys?Prokofiev
Yeah it is more robust and concise enoughLibbie
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 propertiesBeforehand
E
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;
}
Expense answered 13/4, 2012 at 9:0 Comment(2)
does not work <script> if(!isset(res)){ alert('not set') } alert('go to here') </script>Pelvic
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.Expense
M
5

typeof will serve the purpose I think

if(typeof foo != "undefined"){}
Mirage answered 20/11, 2010 at 8:6 Comment(1)
Note, however, that typeof null == 'object' - just another one of the quirks of JavaScript.Phosphate
A
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.

Alembic answered 20/11, 2010 at 8:18 Comment(1)
Clever, but only useful if you know which object you are working on.Estheresthesia
P
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 :)

Pereira answered 9/12, 2015 at 17:10 Comment(0)
S
3

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

Selfindulgent answered 20/11, 2010 at 8:6 Comment(1)
+1. Speed is everything in Js...Selfindulgent
P
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.

Peroxidase answered 20/11, 2010 at 8:6 Comment(0)
T
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:{};
Titular answered 19/12, 2013 at 8:23 Comment(2)
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.Titular
Another netbeans shortcut: (abbreviation: set) ${variable} = isset(typeof(${variable}))?${variable}:{};Titular
D
0

Here :)

function isSet(iVal){
 return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
Defence answered 21/4, 2014 at 17:19 Comment(2)
You may want to add additional details as to why this will help the OP.Befit
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 futureRadiobroadcast
P
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").

Papillose answered 15/6, 2014 at 16:39 Comment(0)
R
-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 
}
Reinke answered 5/3, 2014 at 9:20 Comment(2)
@user9 if 0 it will go to else because 0 is equal to falseReinke
and that can be a non desired behavior and not analog to issetCling

© 2022 - 2024 — McMap. All rights reserved.