Here's how things look like in modern Javascript.
In respect to loops, all values can be divided into "iterable" and "non-iterable". Iterable are values that you can well... iterate - with the for..of
loop.
for (let item of someIterableThing)
// use item
(You do not use bare for
loops - for(var i...i < length)
- for the iteration, because not every iterable has length
and indexes.)
Conversely, if you do for...of
with a non-iterable thing, you'll get an error.
Arrays and strings are examples of iterable values, numbers are non-iterable. So when you have
[ [1,2], [3,4], "foobar" ]
all items in this array are iterable and your nested loop will work. However, in
[ [1,2], [3,4], 999]
the last item is non-iterable, and the nested loop will fail.
There's no built-in way to tell if an unknown value is iterable, you have to write a function for this:
let isIterable = x => x && x[Symbol.iterator]
(see the dedicated topic).
Then, you can use the nested loop in a safe manner:
for (let item of array)
if (isIterable(item))
for (let subItem of item)
console.log(subItem)
else
console.log(item)
As a side note, there are lots of obsolete information about Javascript on the net. The language is evolving, and things that were fine 5 years ago, are considered bad practice nowadays. Unfortunately, most tutorials, books and teachers do not keep up, and still promote old practices, like using bare for
loops.
(Since people asked why exactly bare for
loops are bad, consider this example:
You have an array text
containing strings and multiple functions that process this array. Programmer A writes these functions in the old-fashioned manner:
for (var i = 0; i < text.length; i++)
do_something_with(text[i]) // ;(
Programmer B writes them in the modern way:
for (let str of text)
do_something_with(str) // :)
Now, the text
grows bigger and bigger and doesn't fit in memory anymore. So the system architect decided to replace it with a streamable file object that only yields one string at a time. Programmer A now has to rewrite all his 100 functions to adapt to the new interface:
for (var file = TextFile; !file.eof(); file.getNext())
do_something_with(file.currentLine)
which involves lots of pain, convulsions and headache.
Programmer B just enjoys her vacation.)