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!

adiga
  • 34,372
  • 9
  • 61
  • 83
paul
  • 1
  • 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} ]; }` – Heretic Monkey May 26 '21 at 18:57
  • 1
    Does this answer your question? [How to add an object to an array](https://stackoverflow.com/questions/6254050/how-to-add-an-object-to-an-array) – Heretic Monkey May 26 '21 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"*. – Felix Kling May 26 '21 at 19:13
  • Thanks for the help everyone! :) – paul May 26 '21 at 19:16

2 Answers2

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).

Spectric
  • 30,714
  • 6
  • 20
  • 43
Tom O.
  • 5,730
  • 2
  • 21
  • 35
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;
})();
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79