r/learnjavascript • u/OsamuMidoriya • Jul 11 '24
debugging problem
My teacher was telling us about debugging, and how it's basically figuring out why a code is not working and that's what we will be spending most of our time on the job doing. He gave us the example below. we come into work and a coworker gives us this code because its not working(it works),together we was worked on it step by step what it does. NOTE this is not original we renamed something to make it easier to read.
I understand what this code does, the problem I am having is the [] at the end of the function.
const flattend = [[0, 1], [2, 3], [4, 5]].reduce{
(accumulator, array) => accumulator.concat(array), []);he said that the code is saying the accumulator should start off as an empathy array [] and it basically saying
(accumulator, array) => [].concat(array), []);I'm not sure why or how the [] is the accumulator, because of this I'm now unsure how to tell what the perimeter will be in any code
3
u/sepp2k Jul 11 '24
So you see that
[]is passed as the second argument ofreduceand you want to know what that means, right? So what you do in that situation is you look up the docs for reduce where you'll see this:and then, further down, this:
So that's how you know that
reduce's second parameter is the starting value for the accumulator and it's also how you find out what any other parameter to any other standard library function does: you look it up in the documentation.1
u/tapgiles Jul 12 '24
You can look up with reduce does here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce and concat: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat to understand how it works.
original_array.concat(new_array) would return a new array that contains all items from original_array and all items from new_array.
original_array.reduce(callback_fn) calls the callback with the accumulated object and each object in the original array one at a time, and keeps what is returned as the new accumulated object.
So the code:
Will do this, step by step:
That's about it.
1
u/BadDescriptions Jul 11 '24
Think of it in the form of a for loop
let accumulator = [] <- this is the final []
for (const arrayIrem in array){
accumulator = accumulator.concat(arrayItem)
}
1
u/andmig205 Jul 11 '24
The reduce method returns an accumulator. In your case, the expected value of the const flattened is an array. Hence, the accumulator is, well, an array as well. Note how, on each iteration, the accumulator is modified by using Array.concat method.
Accumulators can be any object depending on the logic needs.