user10727653
user10727653

Reputation:

Array.isArray says to be false

I'm a new javascript learner, currently learning destructuring. My question is in a snippet which I edited a bit. The console says it's an array, but I didn't think it was supposed to be?

1: How is this not an array?

const heroes = [{
  lol: ['l', 'Iron Man']
}]

const [lol, dc] = heroes;
console.log(Array.isArray(lol)); 

2: How is this one an array?

const heroes = {
  lol: ['l', 'Iron Man']
}

const {lol, dc} = heroes;
console.log(Array.isArray(lol));

Upvotes: 1

Views: 180

Answers (3)

Barmar
Barmar

Reputation: 781503

In the first snippet, heroes is an array. The first element of the array is the object

{
 lol:['l', 'Iron Man' ]
}

The destructuring assignment sets lol to this element, and sets dc to undefined because there's no second element in the array. The above object is not an array, so Array.isArray(lol) is false.

const heroes = [{
 lol:['l', 'Iron Man' ]
}]

const [element1, element2 ] = heroes;
console.log(element1); 

In the second snippet, heroes is an object. The destructuring assignment sets lol to the value of the lol property in the object, which is ['l', 'Iron Man']. It sets dc to the dc property; since this doesn't exist, it's set to undefined. Since lolis set to an array,Array.isArray(lol)` is true.

If you want to set lol to the array in the first snippet, you need another level of nesting.

const heroes = [{
 lol:['l', 'Iron Man' ]
}]

const [{lol, dc}] = heroes;
console.log(Array.isArray(lol)); 

Upvotes: 6

Sven.hig
Sven.hig

Reputation: 4519

because the first example you are trying to destructure using [] which is used for destructure arrays, However {} are to be used to destructure an object

so in you case you should first destructure the array first using [] and then inside {} to destructure the object

const heroes = [{
  lol:['l', 'Iron Man' ]
 }]
 
 const [{lol, dr}] = heroes;
 console.log(lol)
 console.log(Array.isArray(lol));

Upvotes: 0

Konstantin
Konstantin

Reputation: 26

in const [lol, dc ] = heroes lol is an object {lol:['l', 'Iron Man' ]} in const {lol, dc } = heroes lol is an array ['l', 'Iron Man' ]

Upvotes: 0

Related Questions