2

While testing some code, I came across some syntax I was not totally familiar with before:

const obj = {
  key: "tree",
  value: "narra"
}

let condition = false;

var x = {...(condition && obj)};

console.log(x);

When I ran the code above I thought, I guess you can spread boolean values. But I tested on other primitive data as well such as integers and even on a function:

let x = {...123};
console.log(x);

x = {...function(){}}
console.log(x)

I always thought that the spread syntax would only work on arrays, objects, & other iterables such as string and would otherwise cause syntax errors. Why does it work in my examples and why do they return void?

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
  • I hope this will be enough to clear your confusions https://www.ecma-international.org/ecma-262/11.0/index.html#sec-runtime-semantics-destructuringassignmentevaluation – Code Maniac Sep 04 '20 at 05:24
  • That it works on booleans and functions is ok with me, but I don't get why it doesn't throw on `null` and `undefined`... https://stackoverflow.com/questions/47155141/spreading-undefined-in-array-vs-object – Kaiido Sep 04 '20 at 05:52

1 Answers1

3

Object spread is just syntactic sugar for Object.assign. Object.assign converts every source value to an object, just like what happens if you tried to access a property on a primitive value.

However, the objects created from primitives don't have own properties:

console.log(Object.getOwnPropertyNames(false));

(how could they, they are primitives after all (all their properties come from their prototype))

so it doesn't really have effects on the final result.

As for functions, Object.assign only considers enumerable properties and none of the default properties of a function is enumerable.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143