-1

while coding I very often check if an array is empty by using JSON.stringify

It works the whole time but I am using it very often and dunno if it is proper to work with JSON.stringify to check if the array is empty.

Example:

var arr = [];
if(JSON.stringify(arr) == "[]"){
   alert("Array is empty);
}

My question is not how to check if an array is empty. I ask if it is correct or inefficient in doing it that way I use it.

I know that there are plenty of ways to check if an array is empty.

Thanks

mbijou
  • 87
  • 1
  • 2
  • 12
  • 3
    why not arr.length == 0? – Dinesh undefined Jun 15 '17 at 02:42
  • 4
    This is a very wasteful way to check if the array is empty, particularly when the array happens to be large. Use `arr.length`. – jfriend00 Jun 15 '17 at 02:45
  • Thank you for your answer! I know there are many possible ways. The reason I ask is that I have implemented this one in my code and I want to know if this method is also correct. If it is false I will correct my code. Thank your very much ! – mbijou Jun 15 '17 at 02:45
  • 1
    *"I want to know if this method is also correct. If it is false I will correct my code."* - You should change to using `arr.length` regardless of what other methods may work, because all other options are worse. – nnnnnn Jun 15 '17 at 02:46
  • 1
    It's not incorrect, in the sense that it will provide you with right the answer. However it's an expensive way to achieve it. – Evan Trimboli Jun 15 '17 at 02:46
  • 1
    Possible duplicate of [Check if array is empty or null](https://stackoverflow.com/questions/7198197/check-if-array-is-empty-or-null) – guradio Jun 15 '17 at 02:46
  • guradio the question is not if an array is empty. The question is if it is correct to check if an array is empty by using JSON.stringify. – mbijou Jun 15 '17 at 02:50
  • the dup is the the way to check if array is empty. dont need to circle around using json.stringify if you can just check the length – guradio Jun 15 '17 at 02:51
  • @mbijou - As Evan said, it's not "incorrect" in that it will give you the right answer, it's just the worst possible way to do it. Please take everyone's advice and use `array.length`. – Michael Geary Jun 15 '17 at 02:56
  • @Kaiido - `new Array(23)` is definitely not an empty array! It is an array of 23 elements, each of which have the value `undefined`. That is not an empty array. It's the same array you would get with `[ undefined, undefined, undefined, ... ]` (where undefined appears 23 times). The _definition_ of an empty array is an array with zero elements, not 23 elements regardless of their values. – Michael Geary Jun 15 '17 at 02:57
  • 1
    @MichaelGeary, nope, it returns an new array with 23 **empty slots** these slots are not set to `undefined`, hence the Array is still empty. – Kaiido Jun 15 '17 at 02:59
  • @MichaelGeary - Further to what Kaiido said, you can see the difference in the way Chrome represents such an array in the console (it says `(23) [undefined × 23]`, *not* `23 [undefined, undefined, undefined, etc.]`). – nnnnnn Jun 15 '17 at 03:00
  • @nnnnnn how would you check if this `new Array(23)` is empty? – guradio Jun 15 '17 at 03:02
  • 2
    Come on, guys, let's stick to the basics and not confuse the OP, who is already confused enough. Neither `new Array(1)` nor `[undefined]` is an empty array! An empty array is one with *nothing* in it, *zero* elements, *zero* slots, **nothing**. Can't we agree on that? Yes, I misspoke when I said that `new Array(1)` and `[undefined]` are *identical*, but neither one is an ***empty*** array. – Michael Geary Jun 15 '17 at 03:05
  • 1
    @guradio - I wouldn't: I rarely use sparse arrays so it just never really comes up. But I guess if you want to distinguish between an array that has empty slots that have never been assigned values and an array that has been assigned all `undefined` values you could say `arr.some((v,i,a)=>i in a)`. – nnnnnn Jun 15 '17 at 03:08
  • @nnnnnn which function should i read on about `arr.some((v,i,a)=>i in a)` from this i cannot understand so i need further reading. – guradio Jun 15 '17 at 03:17
  • To put it another way... Try this: `var a = new Array(23); a.push('x');` - now what is the length of `a`? If `a` were an *empty* array, the length would now be one, wouldn't it? After all, we pushed one element at the end of the "empty" array. But `a.length` is now 24. Doesn't sound like `a` was empty before the `push`, does it? – Michael Geary Jun 15 '17 at 03:19
  • @mbijou - Sorry for the digression on whether `new Array(23)` is an "empty" array. (It wasn't my idea!) I just want to assure you that this question is irrelevant to your concern. `new Array(23)` is not an empty array by any stretch of the imagination, so you can feel safe in ignoring this entire side discussion. – Michael Geary Jun 15 '17 at 03:25
  • @MichaelGeary - In my opinion an array that has slots but no elements is empty for the same reason that most people would say that a bus that has seats but no passengers is empty. The JS array `.length` property doesn't count elements, but given sparse arrays aren't needed often it typically doesn't matter. Note also that some array methods (e.g., `.forEach()` skip empty slots. – nnnnnn Jun 15 '17 at 03:25
  • @nnnnnn - Obviously we need to define our terms. You appear to be using a definition of "empty array" that means "an array of any length, as long as the elements are only 'slots' but don't contain any values". I suggest that this is not the definition of "empty array" that the rest of the world uses - and the `.push('x')` test I proposed bears this out. If you push one element to an empty array, you should get an array of length 1. Do you really disagree with that? – Michael Geary Jun 15 '17 at 03:31
  • 1
    @guradio - I over-complicated it: `arr.some(()=>true)` will do it, because the `.some()` method only checks actual elements, not empty slots. (You asked for further reading: just google the `some()` method, arrow functions, and (for my original comment) the `in` operator.) – nnnnnn Jun 15 '17 at 03:31
  • @nnnnnn happy coding mate :) – guradio Jun 15 '17 at 03:33
  • @MichaelGeary - I see your point. I think it is reasonable. I disagree with it for the reason I already stated. Therefore I propose that we agree to disagree. Note that if you `delete` the last item in an array that doesn't change the `.length` either. Basically, the JS `.length` property doesn't count elements so doesn't give an indication of whether the array is empty, but note that in some languages array length is fixed at declaration time, so what is "empty" in those languages? (That was rhetorical.) But again, your view is also reasonable so let's agree to disagree. – nnnnnn Jun 15 '17 at 03:35
  • @MichaelGeary i tried to log in chrome new array(23) it outputs `(23) [undefined × 23]` how would you define this as compare to var arr = [] which will output `[]` i need to know which definition is for which :) – guradio Jun 15 '17 at 03:36
  • @nnnnnn - I'm sorry I got a little hot-headed with you! Can we chalk it up to enthusiasm? :-) Ultimately we need to define our terms: does "empty array" mean an array of zero length (which is the same as an array that will stringify to `[]`), or is it an array of any length that contains only empty slots and no slots containing array elements? Either of those could be useful definitions depending on the circumstance, but I think the most common definition is an array of zero length. That does seem to be the definition OP was using, based on the stringify test. – Michael Geary Jun 15 '17 at 04:05
  • @guradio - I'm not sure what you are asking in your last comment, can you clarify? – Michael Geary Jun 15 '17 at 04:08
  • @MichaelGeary just asking the correct term for an array `new array(23)` which is any empty array but has length and array which is like `var arr = []` another empty array this time has length 0. I am getting confused now with these two kinds of array :( – guradio Jun 15 '17 at 04:13
  • @guradio - As you can see from this sometimes heated discussion, it's really up to you to decide what it is you want to test for. Do you want to know when an array has zero length - no elements and no slots at all? Or do you want to know when an array of any length (zero or nonzero) has nothing in it but empty slots? In most cases, when people talk about an "empty array" they mean an array of zero length, so you can just test `array.length`. But as @nnnnnn pointed out, there may be a case where you want to know if an array has any elements regardless of its length. That is probably more rare. – Michael Geary Jun 15 '17 at 04:49
  • 1
    @nnnnnn - BTW, despite our disagreement on terminology, I want to say that I admire your tenacity and willingness to explore these edge cases. It reminds me of the old saying... "There are two hard problems in computer science: cache expiration, naming things, and off-by-one errors." – Michael Geary Jun 15 '17 at 04:54

3 Answers3

2
if(arr.length === 0) {
   alert("Array is empty);
}
Yichz
  • 9,250
  • 10
  • 54
  • 92
1

Use Array.length length gives you length of the array.

var arr = [];
if(arr.length == 0){
   alert("Array is empty);
}
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

You can make use of the .length function to check if array is empty or not.

If array have item in it, the length of the array would be more than 0, otherwise, 0.

For example:

var arr = [];

if (arr.length == 0){
   alert("Array is empty");
}
CodeName
  • 559
  • 2
  • 6
  • 23