-3

I inherited some code in a React Native codebase and was just curious as to what this syntax means. Can't seem to find a good answer by googling but I have console logged it seems like:

   const myObject = object2 ? ojbect2 : object1

Is similar to:

   const myObject = { ...object1, ...object2}
Evan Lesmez
  • 59
  • 1
  • 6

2 Answers2

1

This const myObject = { ...object1, ...object2} is called combination of properties from objects using spread sysntax, so you can create objects using the attributes from multiple objects.

For example, the following example illustrates how the function Object.assign and spread syntax are related.

Spread syntax

let object1 = {
  "name": "Ele"
};

let object2 = {
  "from": "Stack"
};

const myObject = { ...object1, ...object2};
// Now myObject is a combination of the previous objects.
console.log(myObject);

Object.assign

let object1 = {
  "name": "Ele"
};

let object2 = {
  "from": "Stack"
};

const myObject = Object.assign({}, object1, object2);
// Now myObject is a combination of the previous objects.
console.log(myObject);
Ele
  • 33,468
  • 7
  • 37
  • 75
-1

The first is logical operators.

const myObject = object2 ? ojbect2 : object1

Which is equivalent to:

const myObject = ()=>{if(object2){return object2}else{return object1}}

For the other, spread syntax, see this page for a description of how that works. It's supposed to be used for expanding objects inline to be passed to any other object/function.

Ele
  • 33,468
  • 7
  • 37
  • 75
joshhemphill
  • 492
  • 6
  • 20
  • 1
    I think you mean: `if(object2){return object2} else {return object1}`. And that's not syntactically correct. It needs to be in a block for ternary for the `else` to work. – David Klinge Apr 25 '19 at 17:28