So what I am doing is trying to understand what const [,] or const [_,,,] does in this for of loop in typescript or javascript. What are these?
function getArr() {
return ['a','b', 'c']
}
for (const [,] of getArr()) {
}
for (const [_,,,] of getArr()) {
}
CodePudding user response:
In your example both for
loops will cause an errors. What you want in JS is called Destructuring assignment. For example you have a function getArr()
which returns an array, but you want to get (for some reason) only first array value. You can use Destrictuing Assignment.
const [first, ...rest] = getArr();
console.log(first) // Will output: 'a'
console.log(rest) // Will output: ['b', 'c']
In your example, in the first loop you're trying to use Destructing Assignment on and variable, not an array, so error will happen. Just look how for...of loop works with arrays. Obviously in the second for..of
loop you trying to do the same, but saving first array element in the variable by the name _
.
CodePudding user response:
function getArr() {
return ['a','b', 'c']
}
for (const item of getArr()) {
console.log(item)
}
Try above code if you access return value from the function