0

Am I being stupid here? (I'm coming from Ruby, so there might be something about Javascript arrays that I'm missing).

console.log(new_devices)

Result in console: Array[1].

console.log(new_devices.length)

Result in console: 0

The code producing this:

var sp = require('serialport');
var new_devices = [];

sp.list(function(err, ports) {
  ports.forEach(function(current) {
    if (current.manufacturer == "Teensyduino") {
      new_devices.push(current);
    }
  });
});

console.log(new_devices);
console.log(new_devices.length);

enter image description here

Alfo
  • 4,801
  • 9
  • 38
  • 51

1 Answers1

2

When you console log arrays the console creates a reference to that array, it does not show you a snapshot of the state of the array at the point of execution.

(In your code items are appended to the list async, so when the console log is printing the list is empty.)

Consider this example:

enter image description here

knutesten
  • 594
  • 3
  • 16