215

I'm looking for a method for JavaScript that returns true or false when it's empty... something like Ruby any? or empty?

[].any? #=> false
[].empty? #=> true
0

14 Answers 14

248

The JavaScript native .some() method does exactly what you're looking for:

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
16
  • 2
    Thank you, I see now [12,5,8,1,4].some(function(e){ return e > 10;}); working!
    – kangkyu
    Commented Jan 5, 2016 at 10:01
  • 6
    @kangkyu I think it's time to accept this answer ;) Commented Aug 5, 2016 at 13:23
  • 4
    Sorry for late response, but @asiniy I still think the accepted answer should have been accepted because it has more details (including some()) and can be more helpful to others.
    – kangkyu
    Commented Nov 3, 2016 at 17:36
  • 10
    @kangkyu Except the currently accepted answer spends more time trying to be Ruby-ish than actually giving a javascript answer. It also recommends writing your own wrapper (which really isn't necessary) and does so in a potentially harmful way (i.e. extending the prototype for something that isn't a polyfill)
    – Jasper
    Commented Oct 12, 2018 at 8:33
  • 2
    @LokiKriasus Extending the prototype may cause future problems (i.e. if in the future javascript defines a any() method, and someone uses it, that code may fail in weird ways when used together with a library that uses this code because you defined it slightly differently) and creates code that is harder to read for other (javascript) developers. And the whole reason for that approach is that a Ruby developer refused to learn that they should write some() instead of any() and that they shouldn't forget to pass a function to it even if the array is empty...
    – Jasper
    Commented Aug 5, 2019 at 8:06
127

JavaScript has the Array.prototype.some() method:

[1, 2, 3].some((num) => num % 2 === 0);  

returns true because there's (at least) one even number in the array.

In general, the Array class in JavaScript's standard library is quite poor compared to Ruby's Enumerable. There's no isEmpty method and .some() requires that you pass in a function or you'll get an undefined is not a function error. You can define your own .isEmpty() as well as a .any() that is closer to Ruby's like this:

Array.prototype.isEmpty = function() {
    return this.length === 0;
}

Array.prototype.any = function(func) {
   return this.some(func || function(x) { return x });
}

Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project.

0
45

I'm a little late to the party, but...

[].some(Boolean)
6
  • 5
    I guess this doesn't play well with [false, 0, '', null, undefined] Commented Sep 25, 2019 at 10:31
  • It works wonderfully, @BrookJordan. It returns false. The zero in there is questionable, but for the rest, I believe that is the functionality OP was after. Looking for "truthy" entities.
    – Dudo
    Commented Apr 18, 2020 at 20:55
  • 3
    another, arguably more beautiful way of writing this: [].some(x => Boolean)
    – phil294
    Commented Aug 12, 2020 at 13:00
  • 12
    @phil294 it should be [].some(Boolean) Commented Sep 22, 2020 at 18:40
  • 1
    [].some(x => Boolean) will always return true, so that won't work. @Gershy is correct, [].some(Boolean) actually does what OP asks. some takes a function to run on every element; Boolean is already a function that converts truthy and falsey values to true and false respectively. So by passing Boolean, some checks every element for truthy/falsey, and handles null, undefined, and empty-string. Commented Jun 11, 2021 at 17:39
17

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false
4
  • 2
    What if empty contains falsy values?
    – Tom Hale
    Commented Nov 9, 2020 at 6:01
  • 3
    empty.some(x => true) would work on [undefined, null, false, 0] Commented Jul 23, 2021 at 17:31
  • @TomHale [false, 0, "", undefined, null, NaN].some(x => x) returns false Commented Nov 20, 2021 at 14:04
  • 1
    If you want to consider those values as valid, use as Holden said: empty.some(x => true) Commented Nov 20, 2021 at 14:33
15
var a = [];
a.length > 0

I would just check the length. You could potentially wrap it in a helper method if you like.

3
  • i think the problem is here if you have a big array you are counting all elements unnecessarily
    – sonertbnc
    Commented Mar 18, 2019 at 21:00
  • @Snr all major interpreters provide efficient accessors for the length of arrays: stackoverflow.com/questions/9592241/… Commented May 19, 2020 at 12:10
  • 1
    This is literally the simplest and best answer beyond all those suggesting to use some. KISS principle!
    – Neo
    Commented Jan 31, 2022 at 9:58
12

JavaScript arrays can be "empty", in a sense, even if the length of the array is non-zero. For example:

var empty = new Array(10);
var howMany = empty.reduce(function(count, e) { return count + 1; }, 0);

The variable "howMany" will be set to 0, even though the array was initialized to have a length of 10.

Thus because many of the Array iteration functions only pay attention to elements of the array that have actually been assigned values, you can use something like this call to .some() to see if an array has anything actually in it:

var hasSome = empty.some(function(e) { return true; });

The callback passed to .some() will return true whenever it's called, so if the iteration mechanism finds an element of the array that's worthy of inspection, the result will be true.

5

Just use Array.length:

var arr = [];

if (arr.length)
   console.log('not empty');
else
   console.log('empty');

See MDN

4

If you really want to got nuts, add a new method to the prototype:

if (!('empty' in Array.prototype)) {
  Array.prototype.empty = function () {
    return this.length === 0;
  };
}

[1, 2].empty() // false
[].empty() // true

DEMO

4
  • Thank you for help. I found here for Array.compact (I live in Ruby area) and they say !!(anything truthy) returns true, so it could be something like !!array.filter(function(e){ return e }).length ?
    – kangkyu
    Commented Feb 7, 2015 at 1:34
  • if (!('any?' in Array.prototype)) { Array.prototype.any? = function () {return !!this.filter(function(e){ return e }).length;};} .... I tried this didn't work urgh
    – kangkyu
    Commented Feb 7, 2015 at 1:48
  • Why don't you use georg's? Also, I don't think you can have question marks in method names.
    – Andy
    Commented Feb 7, 2015 at 2:23
  • 1
    if (!('any' in Array.prototype)) { Array.prototype.any = function () {return !!this.filter(function(e){ return e }).length;};} this works as Array.any() Thank you Andy
    – kangkyu
    Commented Feb 7, 2015 at 23:14
4

What you want is .empty not .empty() to fully mimics Ruby :

     Object.defineProperty( Array.prototype, 'empty', {
           get: function ( ) { return this.length===0 }
      } );    

then

[].empty //true
[3,2,8].empty //false

For any , see my answer here

3

polyfill* :

Array.prototype.any=function(){
    return (this.some)?this.some(...arguments):this.filter(...arguments).reduce((a,b)=> a || b)
};

If you want to call it as Ruby , that it means .any not .any(), use :

Object.defineProperty( Array.prototype, 'any', {
  get: function ( ) { return (this.some)?this.some(function(e){return e}):this.filter(function(e){return e}).reduce((a,b)=> a || b) }
} ); 

__

`* : https://en.wikipedia.org/wiki/Polyfill

2

Array has a length property :

[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6
1

As someone suggested in one of the comments, checking if an array contains any elements can be done with a simple use of some.

let hasItems = array.some(x => true);
let isEmpty = !array.some(x => true);
1
// test data
const data = [[1,2,3,4,5,6],[], [1,7,10]];

// function to check if any condition is satisfied
const any = (condition) => (data) => data.some(condition);

// function to check if empty
const empty = (data) => !data?.length

data.forEach((f) => {
    console.log(`any ${JSON.stringify(f)} -> ${any(x => x %7 == 0)(f)}`);
    console.log(`empty ${JSON.stringify(f)} -> ${empty(f)}`);
});
1
  • Please take a look at the formatting options available for code on Stack Overflow
    – phuzi
    Commented Apr 3 at 14:38
-1

Just use ternary operator

let myArray = []
myArray && myArray.length ? console.log(true) : console.log(false)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.