

Var button = document.createElement("button") īutton. const buttonsContainer = document.getElementById("buttonsContainer")

This is where I added five buttons dynamically using for loop in the JavaScript code below. Bonus: Declare Callback function outside of the loopĪs you can see, the HTML page has a div element with an id called buttonsContainer.Solution #3: Use forEach instead of for.The forEach native Javascript function is basically a function that has a loop inside it and will use an iterator function (callback) to execute over each item inside the collection (the collection may be an array or an object). Solution #2: Closure Outer Function Returns Inner Function The best way to understand the forEach method is creating it from scratch.You can loop over generic iterables with each. Why i variable always get the last index in a loop? The expression ( cats, in this case) can be any array or array-like object (i.e.This is one of the common problems developers face when they start learning JavaScript.īy the end of this article, you will know what causes this issue and some of the ways to fix it. When you attach multiple click events to elements such as buttons inside a for loop, the click event will always give us the last index value regardless of what button is pressed.
