Button click should add items to array, but array is empty on each function call

Viewed 773

Code looks something like this

let sectionWithLimitItems = [];

function addItems(productId) {
     sectionWithLimitItems.push(productId)
}

<button onclick='appendItems({{ productId }})'>Click Me</button>

Working with liquid, Shopify's theme template language, but not sure if that would create complications. If I log the array each time the function is called, it is empty after at the start of the function and can see the id gets added but the array is empty again on the next button click. Any ideas?

-- Edit - sorry for the mistake everyone! I did have arr.push in my code, not append. Wasn't thinking correctly when I made the post. Still having the same issue with sectionWithLimitItems.push(productId)

3 Answers

In javascript you don't use Array.append(), you should use Array.push() (MDN Reference) instead.

I think you might be looking for Array.push()

const sectionWithLimitItems = [];

function appendItems(productId) {
    sectionWithLimitItems.push(productId)
}

<button onclick='appendItems({{ productId }})'>Click Me</button>
Related