Home > Software engineering >  How to add property name in JS via using push?
How to add property name in JS via using push?

Time:04-26

The below js snippet runs successfully. But if I try to not use any function; like addingTOobject_a used below; my program fails to run...

SUCCESSFUL SNIPPET ->

let a = [];

function addingTOobject_a(x, y){
    a.push({x, y});
}

console.log(a);

addingTOobject_a(["be", "happy"], false);
addingTOobject_a(["stay", "pretty"], true);
addingTOobject_a(["he", "is", "me"], false);

console.log(a);

UNSUCCESSFUL SNIPPET ->

let a = [];

a.push({x,y});

console.log(a);

a.push(["be", "happy"], false);
a.push(["stay", "pretty"], true);
a.push(["he", "is", "me"], false);

console.log(a);

CodePudding user response:

You need to define values for x and y somewhere.

If you aren't going to define x and y variables and then use them as shorthand properties in your object, then you need to define them at the same time as you define the object.

a.push({ 
    x: ["be", "happy"], 
    y: false
});
  • Related