Is it safe to use this kind of loop in Javascript?
denseArray = [1,2,3,4,5, '...', 99999]
var x, i = 0
while (x = denseArray[i++]) {
document.write(x + '<br>')
console.log(x)
}
document.write('Used sentinel: ' + denseArray[i])
document.write('Size of array: ' + i)
It is shorter than a for-loop and maybe also more effective for big arrays, to use a built in sentinel. A sentinel flags the caller to the fact that something rather out-of-the-ordinary has happened.
The array has to be a dense array to work! That means there are no other undefined
value except the value that come after the last element in the array. I nearly never use sparse arrays, only dense arrays so that's ok for me.
Another more important point to remember (thank to @Jack Bashford reminded) is that's not just undefined as a sentinel. If an array value is 0, false, or any other falsy value, the loop will stop. So, you must be sure that the data in the array does not have falsy values that is 0
, ""
, ''
, ``, null
, undefined
and NaN
.
Is there something as a "out of range" problem here, or can we consider arrays in Javascript as "infinite" as long memory is not full? Does undefined mean browsers can set it to any value because it is undefined, or can we consider the conditional test always to work? Arrays in Javascript is strange because "they are Objects" so better to ask.
I can't find the answer on Stackoverflow using these tags: [javascript] [sentinel] [while-loop] [arrays]
. It gives zero result!
I have thought about this a while and used it enough to start to worry. But I want to use it because it is elegant, easy to see, short, maybe effective in big data. It is useful that i
is the size of array.
UPDATES
- @Barmar told: It's guaranteed by JS that an uninitialized array element will return the value undefined.
- MDN confirms: Using an invalid index number returns undefined.
- A note by @schu34: It is better to use
denseArray.forEach((x)=>{...code})
optimized for it's use and known by devs. No need to encounter falsy values. It has good browser support.