I'm trying to understand how the get item at index works in an array in JavaScript.
For example imagine I have a for iterating an array with thousands (or millions) of items. Which would be the best way (with the best performance) to print the items?
// Option 1
for (int i = 0; i < array.length; i++) {
var data = array[i];
console.log( data.ID, data.name, data.date, data.description );
}
// Option 2
for (int i = 0; i < array.length; i++) {
console.log( array[i].ID, array[i].name, array[i].date, array[i].description );
}
Is it option 1 or option 2? Or is it the same thing to use the first or second option? Or is there an even better way to do this?
I know for instance that get() in the Java ArrayList works this way, so obviously the best approach would be option 1, since it checks the range each time it calls the get() method.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
Does JavaScript works in a similar way?
The "big question" here is really how does JavaScript array get item at index works
Note: I've tried to search for the best way to get an element in an array, but all I could find was the best way to iterate an Array. That isn't what I'm trying to get from this question!
console.log, then the best way is applyconsole.logat whole array:console.log(array), orconsole.log(jSON.stringify(array))