0

Here is my code:

var myObject = [];
function something() {
    myObject.push("thing");
}

function other() {
    console.log(myObject);
}

How can I let other see the items pushed into myObject by something?

2
  • console.log(myObject[0])? Commented May 22, 2019 at 21:23
  • 1
    I do have the feeling that you execute other before something ... Commented May 22, 2019 at 21:28

1 Answer 1

1

It's declared globally - so just calling something() then other() will ensure that there are elements in the array. If you were calling them in the wrong order, then the function was displaying the empty array first, then adding an element to it.

var myObject = [];

function something() {
  myObject.push("thing");
}

function other() {
  console.log(myObject);
}

something();
other();

If you want to log each item on a separate line:

var myObject = [];

function something() {
  myObject.push("thing");
}

function other() {
  myObject.forEach(e => console.log(e));
}

something();
something();
something();
other();

Also, you're dealing with an array, not an object. An object looks like this:

var anObject = {
  key1: "value1",
  key2: true,
  key3: 42.01
};

console.log(anObject);

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

5 Comments

and when i have declared globally but i have function in function and want to call it in other function?
"this happens by default" what happens by default? Also are you sure that the question in its current state can be answered already?
i have this but ready function cant read that from message function. pastebin.com/EAqpQtzf - either is array declared, i missed that
Sorry @JonasWilms - I meant to add the function order. I'll edit my answer.
Edited @JonasWilms

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.