1

I want to understand how objects work in JS.

const obj = { inner: { a: 'Hello' } };

const clone = { ...obj };

// obj === clone -> false
// !!! BUT !!!
// obj.inner === clone.inner -> true

clone.inner = { a: 'world' };
// obj === { inner: { a: 'Hello' } }
// clone === { inner: { a: 'World' } }

Is there a documentation on this behaviour? Can I rely on inner objects references equality while creating new object via spread operator?

1
  • only the outer objects are cloned with spread operator. the inner objects will still be references. Commented Sep 30, 2019 at 15:59

2 Answers 2

4

... spread syntax creates a shallow copy anything deeper then level one will still stays as reference to original object

const obj = { inner: { a: 'Hello' } };

const clone = { ...obj };


console.log(obj === clone)

console.log(obj.inner === clone.inner)

Sign up to request clarification or add additional context in comments.

Comments

1

Shallow Cloning If the item being spread into the target is an object, only a reference to that object will be copied. The spread operator will not recursively deep clone properties. In addition, only own, enumerable properties are copied.

This Post will help Link

1 Comment

I found more detailed answer here in the drawbacks section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.