const [a, b, c] = array;
const {a, b, c} = array;
Q: what is the difference here in both the statements?
The difference between “{}” and “[]” is that {} is an empty array while [] is a JavaScript array, but there are more! In JavaScript, almost “everything” is an object. All JavaScript values, except primitives, are objects.
Arrays are Not Constants The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Const is the variables declared with the keyword const that stores constant values. const declarations are block-scoped i.e. we can access const only within the block where it was declared. const cannot be updated or re-declared i.e. const will be the same within its block and cannot be re-declare or update.
The first is iterable destructuring. a
will get the first value in array
, b
will get the second, and c
will get the third.
The second is object destructuring. a
will get the value of array.a
, b
will get the value of array.b
, and c
will get the value of array.c
. (Not usually what you want with arrays.)
Example of the first:
const [a, b, c] = ["ay", "bee", "see"];
console.log(a, b, c);
That example uses an array, but the source can be any iterable object.
Example of the second (object destructuring), with an array:
const array = ["ay", "bee", "see"];
const {a, b, c} = array;
console.log(a, b, c);
In the normal case, of course, those will all be undefined
(as they are above), because arrays don't normally have those properties.
Example of the second (object destructuring), with a non-array object:
const obj = {a: "ayy", b: "bee", c: "see"};
const {a, b, c} = obj;
console.log(a, b, c);
You don't normally use object destructuring with arrays, although you can, since arrays are objects. The times it's useful are when you want to pick out specific entries from the array, such as this code picking out the values at indexes 2 and 4:
const array = ["ay", "bee", "see", "dee", "eee"];
const {2: c, 4: e} = array;
console.log(c, e); // "see" "eee"
You can even do that with indexes from a variable using computed property notation in the destructuring pattern:
const array = ["ay", "bee", "see", "dee", "eee"];
const indexA = Math.floor(Math.random() * array.length);
const indexB = Math.floor(Math.random() * array.length);
const {[indexA]: a, [indexB]: b} = array;
console.log(`${indexA}: ${a}, ${indexB}: ${b}`); // Varies depending on the random indexes
More on MDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With