Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  144] [ 1]  / answers: 1 / hits: 195344  / 10 Years ago, thu, february 5, 2015, 12:00:00

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

More From » javascript

 Answers
18

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.


[#67930] Wednesday, February 4, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;