Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array returns length 0 [duplicate]

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

like image 541
Alfo Avatar asked Dec 20 '25 10:12

Alfo


1 Answers

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

like image 86
knutesten Avatar answered Dec 22 '25 23:12

knutesten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!