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? 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

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

Why assign global.arrayOfObjects = [] and then immediately assign the same variable something else?
@jfriend00 I really don't suggest it... but the OP wanted to... maybe I will update the answer with an observation too, thanks
@jfriend00 I think it is better now, don't you think?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.