0

If I enter the code line by line in a web console without the function() wrap (I use Chrome), it does what I want it to do, but I'm a bit stumped on why the code itself is returning 'undefined' as a block itself:

function () {

var x = [];

x[0] = {'first': 1, 'second': 2, 'third': 3};

return x;

}

I tried pushing the object with the x.push() function, but I don't think that really works either - many articles I've researched say I cannot use the .push() function with javascript objects. Basically I want the code to return:

[ {'first': 1, 'second': 2, 'third': 3} ]

Appreciate your help!

4
  • You've not given the function a name. How are you planning on calling the function? Note that you could also define the function as function makeMeAnArray() { return [ {'first': 1, 'second': 2, 'third': 3} ]; } Commented May 26, 2021 at 18:57
  • 1
    Does this answer your question? How to add an object to an array Commented May 26, 2021 at 19:00
  • Functions need to be called. If you just declare the function in the console (without syntax errors) then it will print undefined. But it's not clear what exactly you mean with "why the code itself is returning 'undefined' as a block itself". Commented May 26, 2021 at 19:13
  • Thanks for the help everyone! :) Commented May 26, 2021 at 19:16

2 Answers 2

1

You need to name your function in order to call it (or use an IIFE). See the example below:

function doExample() {
  const obj = {
    'first': 1,
    'second': 2,
    'third': 3
  };
  const arr = [];

  arr.push(obj);

  return arr;
}


console.log(doExample());

Aside from not naming and calling calling the function, the code in your example looks like it should work fine - so you could use that as alternative to Array.prototype.push (demonstrated above).

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

Comments

0

are you looking for an iife? immediately invoked function expression?

(function () {
var x = [];

x[0] = {'first': 1, 'second': 2, 'third': 3};
console.log(x);
return x;
})();

Comments

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.