Utilizing a "higher order function" such as filter
instead of traditional looping can often result in quicker, safer, and more readable code. In this scenario, filtering the array to eliminate non-empty string items and then checking the length of the resulting array can be beneficial.
Simple JavaScript Approach
var my_arr = ["", "hi", ""]
// keep only the empty string items
new_arr = my_arr.filter(function(item) {
return item === ""
})
// if the filtered array is not empty, there are empty strings present
console.log(new_arr);
console.log(new_arr.length === 0);
Modern Javascript: One-liner
var my_arr = ["", "hi", ""]
var result = my_arr.filter(item => item === "").length === 0
console.log(result);
A note on performance considerations
In situations where speed is crucial, looping may be more efficient since it allows for early termination upon encountering an empty string. Nonetheless, opting for filter
could be preferable for conciseness and clarity of the code, with valid arguments for either approach.
If iterating through all elements in the array were necessary—perhaps to ascertain if every item is the empty string—using filter would likely outperform a conventional for loop!