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; } |
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.
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?
@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...
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'.
@ Knoxius: Sometimes the most simple functions require the most insane JavaScript code. Seen echo ? ;)
@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).
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.
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.
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(){}}
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;
}
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
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.


Brett Zamir
Jun 21st