Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mary Healy
7,818 Pointshow to access the value inside a for loop/function
Hi There,
I cannot access the the value inside the for loop. When I console.log inside the loop I get values returned. However when I console.log outside the loop I get an empty array. I have done some research and it is something to with my anonymous function and closure. But i don't understand how I can access the inputValue outside the loop.
const getGuess = document.querySelectorAll('#game-list li'); const guess = [];
for(let i = 0; i < getGuess.length; i++) { getGuess[i].onclick = function () { let index = guess.indexOf(this.innerHTML); inputValue = this.innerHTML; guess.push(inputValue); console.log(inputValue); console.log(guess); }
}
console.log(guess)
1 Answer
Dario Bahena
10,697 PointsWhat video or task is this for? In essence though, you are assigning a function to each li's onclick handler. That means that whenever that item is clicked, the inputValue will be added to the guess array. The problem is that when you run this, the last console.log has already run. This is more of a logic error. I will add the order of execution for how this will run in the real world (not necessarily what happens "under the hood")
const getGuess = document.querySelectorAll('#game-list li'); // first
const guess = []; // second
let inputValue;
for (let i = 0; i < getGuess.length; i++) {
getGuess[i].onclick = function() { // technicaly, this is added before the last console.log however, it only executes when the item is clicked. So this wont execute.
inputValue = this.innerHTML;
guess.push(inputValue);
console.log(inputValue);
console.log(guess);
}
}
console.log(guess) // third (guess is declared an empty array so it prints empty and will only run once)
Mary Healy
7,818 PointsMary Healy
7,818 Pointsthanks Dario. this has been super helpful. it was a project i am doing for myself.