0
votes

This isn't a technical problem that needs a solution but more that I'm wanting a better technical understanding of JavaScript and recursive functions.

I wrote a recursive function to call an API to get all the records until there were no records left to get.

Below is its basic working form. That returns the expected number of records in the array.

async function getRecords(page, recordsArray) {
    const records = await <axios api call>
    const moreRecords = records.more_records
    if(!moreRecords) {
        return recordsArray.concat(records.data)
    } else {
        return await getRecords(page + 1, recordsArray.concat(records.data))
    }
}

However, when I originally wrote this function I did it like the one below which didn't return the expected number of records and I don't really understand why. I expected it would.

async function getRecords(page, recordsArray) {
    const records = await <axios api call>
    const moreRecords = records.more_records
    if(!moreRecords) {
        recordsArray.concat(records.data)
        return recordsArray
    } else {
        return await getRecords(page + 1, recordsArray.concat(records.data))
    }
}

QUESTION

Why did the second not return the expected number of records but the first did?

1

1 Answers

2
votes

concat does not modify the existing array; rather, it returns a new array.

const arr = [1, 2, 3];
const newArr = arr.concat([4, 5]);
console.log(arr);
console.log(newArr);

If you wanted to tweak your second snippet to work, without using the first snippet instead, push the items from records.data to the recordsArray so that the original array, when returned, contains the new items:

    if(!moreRecords) {
        recordsArray.push(...records.data)
        return recordsArray
    } else {