Use PHP functions in JavaScript

JavaScript isset

!No description available for isset. @php.js developers: Please update the function summary text file.

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
function isset () {
    // !No description available for isset. @php.js developers: Please update the function summary text file.
    // 
    // version: 1008.1718
    // 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;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
isset( undefined, true);

Should return

1
false

» Example 2

Running

1
isset( 'Kevin van Zonneveld' );

Should return

1
true

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have isset goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
Jul 30th Permalink

q  @Rafał Kukawski: I agree with you that certain items should be allowed (my pet peeve is switch case fall-throughs which I'd like to allow "fall-through" comments to insist it was intentional though not requiring even that comment if cases are on the same line).

The real solution here I think is for someone to confirm whether JSLint is open source or not (I couldn't see that it was, though one site claimed it was BSD); if it isn't, we also need a good open source JS parser. Then configure it to make the exceptions we believe in. But since I'm short of time to do this now, I for one hope we will stick with a mostly JSLint-compliant set-up so we don't get used to too many warnings and then miss out on actually useful warnings.

Btw, I took your nice optimization as it is shorter, but as far as timing goes, Firefox testing seemed to have it perform about the same for each no matter the number of arguments. Still, a little less bandwidth wouldn't hurt.

Gravatar
Rafał Kukawski
Jul 28th Permalink

q  @Brett Zamir:
I agree that lint helps in many cases and should be respected in as many cases as possible, and strict rules are good for complex projects where many developers are involved, but sometimes we come across situations where a problem can be solved better when using non-lint compliant solutions. That is why IMO some exceptions should be allowed, especially when the developer is 101% sure of what he is doing (and a good example is the isset function, where it can be improved by using only _core features_ of javascript). But, if being lint compliant is priority for phpjs project than I have to accept your point of view and I'll try to avoid lint warnings in future improvements.

Below another approach to isset. The idea is to declare a var that holds undefined and compare arguments to null and to the undef variable. It might be slower (comparing to current solution) when checking only one argument, but should get faster when checking two or more variables, cause we are avoiding string comparison.

function isset(){
   var a=arguments, l=a.length, i=0, undef;

   [...]
      if(a[i] === null || a[i] === undef)
   [...]
}

Gravatar
Brett Zamir
Jul 28th Permalink

q  @Rafał: Thanks for the ideas. I've applied your latter change, but in my view at least, while more succinct (and getting jslint to be quiet--which actually _is_ a pragmatic goal despite what some people say, given that a minimum of jslint complaints helps spot real errors), I do like the specificity of spelling it out, as it communicates that the issue was considered and addressed.

Gravatar
Rafał Kukawski
Jul 28th Permalink

q  Sorry for the double comment, but wanted to add, that the else clause can be removed. Just leave the i++;

Gravatar
Rafał Kukawski
Jul 28th Permalink

q  IMO, the if statement can be changed to

if (a[i] == null)


it will throw a lint warning, but only null and undefined equals null, so the == operator is used on purpose and the warning can be ignored.

Gravatar
iia
Jul 27th Permalink

q  Thank you, you guys are great!

Gravatar
abc
May 14th Permalink

q  puriyala

Gravatar
mk.keck
6 Mar '09 Permalink

q  Function isset() does not work?
I've done follow test:
[CODE="Javascript"]
if (!isset(a)) { // a does'nt really exists
alert('Var \'a\' is undefined');
} else {
alert('Var \'a\' = "' + a + '"');
}
[/CODE]
I get an Error from browser 'a is undefined'.
If I use isset('a') I get alwasy true ... ?

I've changed the function isset():
[CODE="Javascript"]
function isset() {
var a = arguments;
if (a.length > 0) {
var i = 0;
while (i !== a.length) {
if (typeof(a[i]) === 'object') {
if (typeof(a[i]) === 'undefined' || a[i] === null) {
return false;
} else {
i++;
}
} else if (typeof(a[i]) === 'string') {
if (typeof(window[a[i]]) === 'undefined' || window[a[i]] === null) {
return false;
} else {
i++;
}
}
}
return true;
}
return false;
}
[/CODE]
Now I get the correct answer from function isset

Gravatar
Kevin van Zonneveld
1 Feb '09 Permalink

q  @ Maxim: :)

Gravatar
Maxim
27 Jan '09 Permalink

q  sorry, it doesn't work in Firebug console,
but works properly in firefox itself.

thanks for good function :)

Gravatar
Maxim
27 Jan '09 Permalink

q  [CODE="Javascript"]
var a=1;
delete a;
isset(a);
[/CODE]
throws:
ReferenceError: a is not defined

Gravatar
Kevin van Zonneveld
27 Aug '08 Permalink

q  @ Onno Marsman: Another great attribution to our project! Thank you so much!

Gravatar
Onno Marsman
11 Aug '08 Permalink

q  1. should return false also on null values like in php
2. should throw an error when no arguments are provided
3. should throw an error when passed arguments are not variables, like in both examples. They would give an error in PHP. Not sure if this is possible or needed by anyone.

Implementation for 1. and 2. :
[CODE ="Javascript"]
function isset() {
var a=arguments; var l=a.length; var i=0;
if (l==0) { throw new Error('Empty isset'); }
while (i!=l) {
if (typeof(a[i])=='undefined' || a[i]===null) { return false; } else { i++; }
}
return true;
}
[/CODE]
I made up an error message because I thought:

Parse error: syntax error, unexpected ')', expecting T_STRING or T_VARIABLE or '$'

Would be pushing it ;)

The check for l==0 could be placed after the while to make it a littlebit more efficient in the case it would return false, but I think this is more readable.

Gravatar
Kevin van Zonneveld
17 Apr '08 Permalink

q  @ FremyCompany: Updated, thank you!

Gravatar
[FremyCompany] Can be maked quicker :
16 Apr '08 Permalink

q  [CODE="Javascript"]function isset() {
var a=arguments; var l=a.length; var i=0;
while (i!=l) {
if (typeof(a[i])=='undefined') { return false; } else { i++; }
}
return true;
}[/CODE]


Contribute a New function

More functions

In this category

doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
» isset
print_r
serialize
settype
strval
unserialize
var_dump
var_export

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !