Why does Javascript spread maintain defined keys that are set to undefined, and how do they differ from non-existent keys?

40 Views Asked by At

I have a code sample below that demonstrates this. I ran into this unexpected behavior of the spread operator where a key that gets set as undefined is not treated the same way keys that have never been defined are. Both have the typeof that is undefined but they are not entirely the same.

I'm trying to understand how/why this is. I've been operating under the mistaken assumption that setting a key's value to undefined is the equivalent of removing the key (e.g. they're both lost if you JSON.stringify their values). Now, I'm trying to understand how they differ and what effects that has on other use cases

Note: I thought this was a Typescript thing but tested again in JS with the same issue.

const obj1 = {a: "apple", c:"crab", d:"dagger", e: undefined};
const obj2 = {a: "aardvark", b:"blue", c: undefined, f: "flamethrower", g: undefined};

const res1 = {
  ...obj1,
  ...obj2
};

const res2 = {
  ...obj2,
  ...obj1
};

const res3 = {
  ...obj1
};

console.log(res1);
console.log('====');
console.log(res2);
console.log('====');
console.log(res3);
console.log('====');
console.log(typeof res3.e);
console.log(typeof res3.h);
console.log(JSON.stringify(obj1));

0

There are 0 best solutions below