Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.


Yes, there is a way:

 var n = 1000;
 Array(n).join(".").split("."); // now contains n empty strings.

I'd probably use the loop though, it conveys intent clearer.

function repeat(num,whatTo){
    var arr = [];
    for(var i=0;i<num;i++){
        arr.push(whatTo);
    }
    return arr;
}

That way, it's perfectly clear what's being done and you can reuse it.

Answer from Benjamin Gruenbaum on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › how-can-i-check-javascript-arrays-for-empty-strings
How can I check JavaScript arrays for empty strings?
var studentDetails = new Array(); studentDetails[0] = "John"; studentDetails[1] = ""; studentDetails[2] = "Smith"; studentDetails[3] = ""; studentDetails[4] = "UK"; function arrayHasEmptyStrings(studentDetails) { for (var index = 0; index < studentDetails.length; index++) { if (studentDetails[index] == "") console.log("The array has empty strings at the index=" + (index)); else console.log("The value is at index="+(index)+"="+studentDetails[index]); } } arrayHasEmptyStrings(studentDetails); To run the above program, you need to use the following command − ... Here my file name is demo210.js. ... PS C:\Users\Amit\javascript-code> node demo210.js The value is at index=0=John The array has empty strings at the index=1 The value is at index=2=Smith The array has empty strings at the index=3 The value is at index=4=UK
🌐
freeCodeCamp
freecodecamp.org › news › check-if-javascript-array-is-empty-or-not-with-length
How to Check if a JavaScript Array is Empty or Not with .length
October 5, 2020 - By Madison Kanna When you're programming in JavaScript, you might need to know how to check whether an array is empty or not. To check if an array is empty or not, you can use the .length property. The length property sets or returns the number ...
🌐
DEV Community
dev.to › talenttinaapi › javascript-why-do-we-get-empty-strings-when-we-compare-them-to-empty-arrays-21ja
Javascript: Why do we get empty strings, when we compare them to empty arrays? - DEV Community
May 3, 2023 - The output of the code console.log([] + []); will be an empty string "". This behaviour can be a bit surprising at first, but it's due to the way JavaScript handles the addition operator (+) when used with arrays.
Top answer
1 of 16
1833

A few simple ways:

var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];

arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Number) 
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Boolean) 
// [1, 2, 3, -3, 4, 4, 5, 6]

or - Classic way: simple iteration

var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
    len = arr.length, i;

for(i = 0; i < len; i++ )
    arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);  // cut the array and leave only the non-empty values
// [1,2,3,3,[],Object{},5,6]

jQuery:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
    
arr = $.grep(arr, n => n == 0 || n);
// [1, 2, 3, 3, 0, 4, 4, 5, 6]
2 of 16
1506

EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the Array.prototype.

Now, certainly, I would recommend you to use the filter method.

Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it.

For example, if you want to remove null or undefined values:

var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];

var filtered = array.filter(function (el) {
  return el != null;
});

console.log(filtered);

It will depend on what you consider to be "empty" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string.

One typical pattern that I see often used is to remove elements that are falsy, which include an empty string "", 0, NaN, null, undefined, and false.

You can pass to the filter method, the Boolean constructor function, or return the same element in the filter criteria function, for example:

var filtered = array.filter(Boolean);

Or

var filtered = array.filter(function(el) { return el; });

In both ways, this works because the filter method in the first case, calls the Boolean constructor as a function, converting the value, and in the second case, the filter method internally turns the return value of the callback implicitly to Boolean.

If you are working with sparse arrays, and you are trying to get rid of the "holes", you can use the filter method passing a callback that returns true, for example:

var sparseArray = [0, , , 1, , , , , 2, , , , 3],
    cleanArray = sparseArray.filter(function () { return true });

console.log(cleanArray); // [ 0, 1, 2, 3 ]

Old answer: Don't do this!

I use this method, extending the native Array prototype:

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);

Or you can simply push the existing elements into other array:

// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
  var newArray = new Array();
  for (var i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
Find elsewhere
🌐
Frank M Taylor
blog.frankmtaylor.com › 2023 › 05 › 04 › weird-javascript-why-do-you-get-an-empty-string-when-you-add-arrays
Weird JavaScript: Why do you get an empty string when you add arrays? – Frank M Taylor
May 4, 2023 - You’re not adding empty arrays. You’re concatenating them. JavaScript will coerce non-strings into strings in order to concatenate successfully.
🌐
Reactgo
reactgo.com › remove-empty-strings-array-javascript
Removing empty strings from an array in JavaScript | Reactgo
March 6, 2023 - To remove the empty strings from an array, we can use the filter() method in JavaScript.
🌐
TutorialsPoint
tutorialspoint.com › in-javascript-how-to-empty-an-array
In Javascript how to empty an array
There are multiple ways to clear/empty an array in JavaScript. You need to use them based on the context. Let us look at each of them. Assume we have an array defined as − let arr = [1, 'test', {}, 123.43]; Substituting with a new array − arr = []
Top answer
1 of 16
5711

Ways to clear an existing array A:

Method 1

(this was my original answer to the question)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

This is also the fastest solution.

This code sample shows the issue you can encounter when using this method:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

A.length = 0

This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

Method 3 (as suggested by Anthony)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

Method 4 (as suggested by tanguy_k)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

Performance

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.

2 of 16
2755

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;
🌐
Sentry
sentry.io › sentry answers › javascript › how do i empty an array in javascript?
How do I Empty an Array in JavaScript? | Sentry
You can set the length property of an array to 0 to empty an array: ... The array length property is readable and writable, so you can use it to get or set the length of an array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › Empty
Empty statement - JavaScript | MDN
An empty statement is used to provide no statement, although the JavaScript syntax would expect one. const array = [1, 2, 3]; // Assign all array values to 0 for (let i = 0; i < array.length; array[i++] = 0 /* empty statement */); console.log(array); // Expected output: Array [0, 0, 0]
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Removing Empty Strings From Array - JavaScript - The freeCodeCamp Forum
August 14, 2022 - I am trying to replicate a recipe app which looks like this: As you can see I need to display the ingredients in a listed form. I have managed to save all the ingredients in an array called items ( codePen Link below…
🌐
LinkedIn
linkedin.com › pulse › surprising-bug-how-empty-string-comma-separated-array-joel-emoh
The Surprising Bug: How an Empty String in a Comma-Separated Array Caused Unexpected Behavior in JavaScript
August 7, 2023 - To fix this issue, we need to filter out the empty strings from the array before using the find() method. We can achieve this by using the Array.prototype.filter() method: See "THE SOLUTION" section on the image above ...
🌐
CoreUI
coreui.io › blog › how-to-check-if-an-array-is-empty-in-javascript
How to check if an array is empty in JavaScript? · CoreUI
February 7, 2024 - An astute question arises: why not rely solely on the length property to determine if an array is empty? The answer lies in JavaScript’s flexibility. Since various data types could technically have a length property, we must first ensure we deal with an array to avoid false positives or negatives. const string = 'Hello World' console.log(string.length) // Output: 11 console.log(Array.isArray(string)) // Output: false
🌐
Koenwoortman
koenwoortman.com › javascript-remove-empty-string-from-array
Remove empty strings from a JavaScript Array
Use the filter() method on arrays to remove empty strings from arrays in JavaScript