-1

so basically i found out that if we create array for example arr1 = [1, 2, 3] and new const { length } = arr1; will going to output 3 but how is this works exactly? is there any more operators instead of { length }? and what are the other use of using const { here some stuff } syntax? i do some research but i didnt find anything that points out this syntax. any assumptions?

  • 1
    `[1, 2, 3]` in javascript is vaguely a shortcut to `{"0": 1, ..."length": 3}` – georg Apr 11 '21 at 14:06
  • 1
    Duplicate of [Javascript object bracket notation ({ Navigation } =) on left side of assign](https://stackoverflow.com/q/26999820/4642212). See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). – Sebastian Simon Apr 11 '21 at 14:11

2 Answers2

1

Basically this is Object destructuring

Basic example:

const user = {
    id: 42,
    is_verified: true
};

const {id, is_verified} = user;

console.log(id); // 42
console.log(is_verified); // true

In your case:

const arr1 = [1, 2, 3]

arr1.length = 3
// Or,
const { length } = arr1

To know more: Object destructuring

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
1

Let examine each line of code :)

const arr1 = [1,2,3]; 

Here, you define an array "arr1", which has 3 elements, so arr1's length is 3. In javascript, arr1 is an object, and 1 of its properties is "length", which reflects the length of the array. So, arr1.length = 3

Now the second line :

const {length} = arr1

Here, we use destructuring assignment to get the property "length" from object arr1. This line is equal to :

const length = arr1.length;

which give you length = 3

Make sense?

You can read more about the destructuring assignment here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33