1

I never used global variables in Node.js so I have trouble understanding why this wont work. I am declaring global variable that is array, than I want to push some object into it and for sake of debugging I just want to stringify it. I tried it like this:

var test = require('./api/test'); //my class
global.arrayOfObjects = []; //declaring array
global.arrayOfObjects.push = new test(123); //docs3._id is something I return from db
console.log(JSON.stringify(global.arrayOfObjects)); //I get []
1
  • 3
    Why did you redefine the .push property to be a new object? Did you mean to call the .push() method?
    – jfriend00
    Commented Jun 1, 2017 at 1:16

2 Answers 2

5

You have to pass the object you want to push into the array as an argument:

global.arrayOfObjects.push(new test(123));

Array.prototype.push() documentation

0
0

You must do one of this three, you are mixin both:

var test = require('./api/test'); 
//global.arrayOfObjects = []; not need to declare the var here
global.arrayOfObjects = new test(123); from db
console.log(JSON.stringify(global.arrayOfObjects));

or

var test = require('./api/test'); 
global.arrayOfObjects = []; //needed to declare with this option
global.arrayOfObjects.push(1);
global.arrayOfObjects.push(2);
global.arrayOfObjects.push(3);
console.log(JSON.stringify(global.arrayOfObjects));

or

global.arrayOfObjects.push(new test(123)); // I think this is the best option
3
  • Why assign global.arrayOfObjects = [] and then immediately assign the same variable something else?
    – jfriend00
    Commented Jun 1, 2017 at 1:17
  • @jfriend00 I really don't suggest it... but the OP wanted to... maybe I will update the answer with an observation too, thanks Commented Jun 1, 2017 at 1:18
  • @jfriend00 I think it is better now, don't you think? Commented Jun 1, 2017 at 1:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.