-1
let size = 1;
let arr = ["a", "b", "c", "d", "e"]

  window.addEventListener("scroll", () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

    if (clientHeight + scrollTop >= scrollHeight - 1) {
      size += 1;
      console.log("adding");
    }
  });

  let items = arr.slice(0, size);
  console.log(items);

This is a dummy array just to showcase the problem. The items array should receive more items from arr array as the user reaches the end of the page.

How can I increase a copy of an array using the variable as an endpoint for an array? I'm trying to run this code above but the items array is not being updated.

This dummy code is a pseudo example of infinite scrolling.

guilhermxlopes
  • 138
  • 1
  • 7
  • 2
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – evolutionxbox Aug 27 '22 at 15:08

1 Answers1

3

The problem has nothing to do with slice. The problem is that the console.log(items); line runs only once and before the scroll event handler runs.

Here is a simpler example that demonstrates the issue. In this case setTimeout()'s handler takes the place of the scroll event handler.

let x = 1;

setTimeout(() => {
  x = 2;
}, 0);

console.log(x); //logs 1 (not 2)
Rocky Sims
  • 3,523
  • 1
  • 14
  • 19