0

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 Answer 1

2

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 {
Sign up to request clarification or add additional context in comments.

1 Comment

Okay, that makes sense which is why returning array.concat(records.data) gives the expected number of records b/c it's returning the new array with the addition records. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.