[javascript] In nodeJs is there a way to loop through an array without using array size?

Let's say I have

myArray = ['item1', 'item2']

I tried

for (var item in myArray) {console.log(item)}

It prints 0 1

What I wish is to have item1 item2

Is there any other syntax that works without using

for (var i = 0; i < myArray.length; i++)

This question is related to javascript node.js

The answer is


Use the built-in Javascript function called map. .map() will do the exact thing you're looking for!


This is the natural javascript option

_x000D_
_x000D_
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
  console.log(value);_x000D_
});
_x000D_
_x000D_
_x000D_

However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
  console.log(item);_x000D_
}
_x000D_
_x000D_
_x000D_

Or you could create an asyncForEach explained here:

https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404


To print 'item1' , 'item2', this code would work.

var myarray = ['hello', ' hello again'];

for (var item in myarray) {
    console.log(myarray[item])
}

In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
    output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
    output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
    output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
    output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
_x000D_
_x000D_

All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 However in es6, you can use for...of safely for iterating over sparse arrays.

See also Are Javascript arrays sparse?.


What you probably want is for...of, a relatively new construct built for the express purpose of enumerating the values of iterable objects:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
  console.log(item);_x000D_
}
_x000D_
_x000D_
_x000D_

... as distinct from for...in, which enumerates property names (presumably1 numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let key in myArray) {_x000D_
  let value =  myArray[key]; // get the value by key_x000D_
  console.log("key: %o, value: %o", key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0 to array.length - 1 rather than using for...in.

So, this is not (as I'd originally thought) an academic question, i.e.:

Without regard for practicality, is it possible to avoid length when iterating over an array?

According to your comment (emphasis mine):

[...] why do I need to calculate the size of an array whereas the interpreter can know it.

You have a misguided aversion to Array.length. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):

loop test

Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.


    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Use Iterators...

var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
    console.log('all done')
})
function processArray(iter, cb) {
    var curr = iter.next()
    if(curr.done)
        return cb()
    console.log(curr.value)
    processArray(iter, cb)
}

More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols