EmreG
EmreG

Reputation: 165

Does ES6/ECMAScript6 destructuring create new variable?

As you know, we use destructuring to use the values in objects with ES6. I wonder about its depth.

When I write the code below:

let (or const) { firstVar, secondVar } = this.props

does it allocate new space in memory or does it use these values like pointers?

In the past, when I wrote

let { options } = this.props
options.splice(0,20)

I noticed that the variable in props had changed although my compiler had errors like 'props are Readonly' on different cases. How could it be possible?

Upvotes: 7

Views: 5026

Answers (2)

user9903
user9903

Reputation:

There is a conflation here between destructuring and splice.

Destructuring will bind a variable to the value contained within the object it is destructuring from.

In your second example, options will be a key on the this.props object; when you print options out, then the original this.props.options object will be used.

So it's a reference; in the way you phrased it, it's a variable that points to another variable.

However, you are also using splice which is a in-place/destructive operation that has side-effects.

slice will return a new array, splice will modify the existing array.

If you want to leave this.props.options alone, you will need to use slice:

let { options } = this.props
options.slice(0, 20) // does not modify the existing array, returns a new array

options.splice(0,20) // modifies the existing array, returns the array of deleted items;

Upvotes: 4

Bergi
Bergi

Reputation: 664297

let and const declare new variables, yes. They are independent from the object property after the assignment/initialisation.

when I wrote let { options } = this.props; options.splice(0,20) I noticed that the variable in props had changed

Yes, that's because your options are an array, and both the variable and the object property point to the very same mutable array instance. Assignment did not copy its contents.

Upvotes: 7

Related Questions