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