Questions on Building a Spreadsheet course

Hi everyone! I have a few questions on a section of the code in the Building a Spreadsheet course.

const range = (start, end) => Array(end - start + 1).fill(start).map((element, index) => element + index);
const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(code => String.fromCharCode(code));

const letters = charRange("A", "J");

Can anyone briefly explain the logic behind the code above?
I don’t understand the reasoning behind Array(end - start + 1). Is this creating an array with only one item inside it?
Also, why do we need to add element + index ? They seem to be two completely different items, in which index represents the positioning of the element in the array.

Thanks~

I suggest you type the following:
console.log(Array(5 - 3 + 1))
and
console.log(Array(5 - 3 + 1).fill(3)
This will show you what this portion of the code will return if the start parameter is set to 3 and the end parameter is set to 5
Then try and work out what element + index will return.
Try console.log(range(3, 5)) to see what you get

1 Like

Thanks @ambradnum for your guidance! I should definitely use more console.log during my learning. I often forget utilizing it. :sweat_smile:

Sorry one more question:
The result of console.log(Array(5)) is (5) [empty × 5].
Is that the format for Array() constructor?
I.e. (number of elements) [ each element in the array] ?

I’m not sure, to be honest. When I try
console.log(Array(5));
I get

[ , , , ,  ]

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.