Use PHP functions in JavaScript

JavaScript empty

!No description available for empty. @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
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
45
function empty (mixed_var) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/empty    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     example 1: empty(null);
    // *     returns 1: true    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    
    var key;    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    } 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }        return true;
    }
 
    return false;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
empty(null);

Should return

1
true

» Example 2

Running

1
empty(undefined);

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 empty 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
Jun 21st Permalink

q  Kevin, I believe dmitriy means filtering via hasOwnProperty inside the for loop. I can make the change, but for this function I wonder whether some users might like to verify that the array/object is _really_ empty (including of prototype-inherited properties). Thoughts? Maybe add an ini_set() configuration option to allow both cases?

Gravatar
Kevin van Zonneveld
Jun 19th Permalink

q  @ dmitriy kulichkin: Could you maybe provide an example?

Gravatar
dmitriy kulichkin
Jun 9th Permalink

q  empty([]) will fail if we extend Array with some methods via prototype. I suppose we should check our keys do not to be function. Does it have a sense?

Gravatar
Brett Zamir
16 Nov '09 Permalink

q  @Stoyan Kyosev: I committed a change at http://github.com/kvz/phpjs/commit/dd40b8850a29c0617a40c7ca5ed2ae90fd720a22 to use the "typeof" check, which doesn't suffer from the same problem (nor will it encourage bad practices for those who see our code and don't know why we're doing it). However, I'm not really sure it is justified to do this for all our other functions which test for it since 1) It takes up a little more space, and 2) JavaScript has quite a few ways for you to redefine things (e.g., var isNaN = 5;). Any opinions? But it doesn't hurt, so there ya go... :) Thanks for the input...

Gravatar
Stoyan Kyosev
16 Nov '09 Permalink

q  As noted in http://www.sitepoint.com/blogs/2009/11/12/google-closure-how-not-to-write-javascript/:

"This function checks if a particular variable has a value defined. Or it does, unless a 3rd party script sets the global undefined variable to something else. "

var undefined = 5; 



"u might think that anyone who assigns a value to undefined deserves what they get, but the fix in this case is trivial: simply declare a local undefined variable for use within the function!simply declare a local undefined variable for use within the function!"

function empty(val) {
var undefined;
return val !== undefined;
};

I suggest to use this "fix" in the current implementation of 'empty'.

Gravatar
Kevin van Zonneveld
14 Apr '09 Permalink

q  @ Knoxius: Sometimes the most simple functions require the most insane JavaScript code. Seen echo ? ;)

Gravatar
Brett Zamir
13 Apr '09 Permalink

q  @Knoxius, PHP.JS is treating objects as associative arrays, including ones without a length property, so that wouldn't work for our project. We are also attempting to mimic PHP behavior fully for those familiar with PHP or wishing to use its approach. For example, your function would not consider any number to be non-empty, whereas PHP only considers 0 as such. Of course, your function might work just fine for your own purposes, but we're trying to build a reliable, consistent API, and PHP is the standard to go by (if we just made our own decisions at every turn, there wouldn't be much justification for sticking to PHP function names, as it'd probably just be more confusing for those who expected it to behave as in PHP).

Gravatar
Knoxius
9 Apr '09 Permalink

q  This version seems a bit complex for the mock-function. Couldn't it be simpler by doing something like this:

function empty(string) {
	if(string.length == 0) {
		return true;
	} else {
		return false;
	}
}



It seems a lot simpler, and it still works perfectly fine.

Example:

var myString = 'This is a string.';

if(empty(null)) { //Returns true
alert("It is empty.");
} else if(empty(myString)) { //Returns false
alert("It is not empty.");
}



There could be something about your code that is better, but it seems a bit too complex for what it could be.

Gravatar
Kevin van Zonneveld
4 Mar '09 Permalink

q  @ Marc Jansen: Fixed in svn, thank you!

Gravatar
Marc Jansen
3 Mar '09 Permalink

q  Nice work folks, but I think I found a bug: shouldn't the following code yield 'false'?

var anObj = { 
  'aFunc' : function () { alert('humpty'); } 
}; 
alert( empty( anObj ) ); // alerts true, but the object contains an element 



This is IMHO wrong for arrays as well:

var anArr = [ 
  function () { alert( 'dumpty' ); } 
]; 
alert( empty( anArr ) ) ; // alerts true, but the array contains an element



Named functions should behave the same.

Gravatar
Kevin van Zonneveld
11 Feb '09 Permalink

q  @ Brett Zamir: wicked

Gravatar
Brett Zamir
10 Feb '09 Permalink

q  If it's all right, Kevin, I'll change the text for !== 'function' to be a test for whether o.hasOwnProperty(i). That solves the prototype problem (though even that might be considered non-empty) but avoids the current issue of considering this to be empty: var o = {method:function(){}}

Gravatar
Brett Zamir
3 Nov '08 Permalink

q  If you like, here's a little bit cleaner and slightly safer implementation, I think:

function create_function (args, code) {
	//$newfunc = create_function('$a,$b', 'return $a + $b;');
	// alert($newfunc(5, 4)); 
	var argmnts = [];	
	argmnts = args.split(/,\s*/);	
	return Function.apply(null, argmnts.concat(code));
}



But if one just wishes an anonymous function, they can just do:

call_user_func_array(function(arg) {...}, $a);



or if they need a string

call_user_func_array(new Function($arg1, $code), $a);



For one behaving more like PHP in returning a global name for the new function:

function create_function (args, code) {
	// $newfunc = create_function('$a,$b', 'return $a + $b;');
	// alert($newfunc); // 'lambda_1'
	// alert(     window[$newfunc](5, 3)    ); // 8 (need window to call it, since the PHP behavior is to return a string)

	var funcName = '';
	if (!this.php_js) {
		this.php_js = {};
	}
	if (!this.php_js.create_function_ct) {
		this.php_js.create_function_ct = 0;
	}
	this.php_js.create_function_ct++;	
	funcName = 'lambda_'+this.php_js.create_function_ct;

	eval(funcName+' = function (' + args + ') { ' +  code + '}');

	return funcName;
}

Gravatar
Francesco
26 Oct '08 Permalink

q  If you extend the Array or Object prototype, empty([]) and empty({}) return true...

i've added
if (typeof mixed_var[key] !== 'function' )
this test before returning false in the for cicle, thanks

Gravatar
Kevin van Zonneveld
6 Oct '08 Permalink

q  @ Onno Marsman: Excellent thought and well executed Onno!

Gravatar
Onno Marsman
6 Oct '08 Permalink

q  typeof array will be 'object' so the check for 'array' maxes no sense:

[CODE="Javascript"]
function empty( mixed_var ) {
if (mixed_var === ""
|| mixed_var === 0
|| mixed_var === "0"
|| mixed_var === null
|| mixed_var === false
|| mixed_var === undefined
|| (mixed_var instanceof Array && mixed_var.length === 0)
) {
return true;
}
[/CODE]

Something else: what about empty({}) ?
If you consider {} an object as in PHP then it will never be empty. But I would never use it like that. It would make more sense to call empty({}) when {} could be considered as an associative array, and in that case it is empty and should return true:

[CODE="Javascript"]
function empty( mixed_var ) {
if (mixed_var === ""
|| mixed_var === 0
|| mixed_var === "0"
|| mixed_var === null
|| mixed_var === false
|| mixed_var === undefined
){
return true;
}
if (typeof mixed_var == 'object') {
for (var i in mixed_var) {
return false;
}
return true;
}
return false;
}
[/CODE]
Note that in this implementation I removed the line that handles arrays because the section that takes care of objects handles this correctly for arrays anyway.

Gravatar
Kevin van Zonneveld
5 Sep '08 Permalink

q  @ Onno Marsman: Thanks again man! Remember if you have a homepage or something, I can add it to the credit sections.

Gravatar
Onno Marsman
4 Sep '08 Permalink

q  should also return true on undefined

Gravatar
IT
26 Jan '08 Permalink

q  Awesome! Exactly what I needed ;)


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 !