I'm reading this Medium article on functional programming and I am seeing a syntax I'm not familiar with. Wondering if anyone can shed some light? It looks almost as if the author is destructuring the entire array into an object, but I don't think that's possible for one, and for two, I'm not sure what purpose it'd serve in this function... Does anyone know what's happening here exactly?
const reduce = (reducer, initial, arr) => {
// shared stuff
let acc = initial;
for (let i = 0, { length } = arr; i < length; i ) {//<-- {length} = arr ??
// unique stuff in reducer() call
acc = reducer(acc, arr[i]);
// more shared stuff
}
return acc;
};
reduce((acc, curr) => acc curr, 0, [1,2,3]); // 6
CodePudding user response:
Array will have a length as property
const x = [1,2,3]; console.log(x.length); // logs 3
And you can destructure the object like below
const obj = {a: 1, b: 2}; const {a, b} = obj; console.log(a, b); // logs 1,2
You can declare new variables by commas initiating with as var, let, const.
'y' is also a let variable below
let x = 0, y = 1;
console.log(x, y) // logs 0, 1
let i = 0, { length } = arr;
is explained as arr is array where it has length as property.let i = 0, {length} = arr; // written in shorthand for declaring the variable
Can be written like
let i = 0;
let {length} = arr;
If you want to destructure an array you won't use
{}
instead you'll be using[]
const arr = [1,2,3,4,5]; const [a, b, ...c] = arr; console.log(a, b, c) // logs 1, 2, [3,4,5]
I hope it's clear now