-2
const army = {
     name: 'karan',
     memb : [
            {
                captain: 'suraj',
            },
            {
                rifleMan: 'sanjay'
            },
            {
                grenadier: 'yogesh'
            }
      ]
}
    
const { name , memb:[, cap]} = army
    
console.log("cap ", cap)

This gives cap { rifleMan: 'sanjay' }.

Can anyone please explain this concept and what it is called

Tom
  • 1,158
  • 6
  • 19
  • What's `cap` in your code? What's the value of `memb:[, cap]`? – Dhana D. Mar 25 '22 at 09:01
  • 3
    [Destructuring assignment - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) -> [Ignoring some returned values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#ignoring_some_returned_values) – Andreas Mar 25 '22 at 09:05

2 Answers2

0

You are de-structuring the army object. So "karen" is stored in name and from the army.memb which is an array you want the second element and store it in cap.

For example if you put two commas it means you want the third element of the memb array:

const army = {
  name: 'karan',
  memb: [{
      captain: 'suraj',
    },
    {
      rifleMan: 'sanjay'
    },
    {
      grenadier: 'yogesh'
    }
  ]
}

const { name, memb: [,, cap]} = army


console.log("cap ", cap)
re-za
  • 750
  • 4
  • 10
0

It is feature of array destructuring in javascript. It is used to ignore or skip certain values while destructuring.

const [a, , b] = [1, 2, 3];
console.log(a,b);   // 1,3
const [, a, b] = [1, 2, 3];
console.log(a,b);   // 2,3
Madhan S
  • 683
  • 1
  • 5
  • 16