Recursive function + concatenation of array unexpected behaviour

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?

44 thoughts on “Recursive function + concatenation of array unexpected behaviour”

  1. 219855 668625Directories such given that the Yellow Websites need not list them, so unlisted numbers strength sometimes be alive more harm than financial assistance. 188306

    Reply
  2. Greetings I am so excited I found your webpage,
    I really found you by accident, while I was searching on Askjeeve for something else, Anyhow I am here
    now and would just like to say many thanks for a tremendous post and a all round
    thrilling blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have book-marked it and also included
    your RSS feeds, so when I have time I will be back to read much more, Please do keep up the
    excellent work.

    Reply

Leave a Comment