How do I put the value of 'index' to a global variable? The value of the index is showing only if its inside the forEach loop, is there a way to take it out and put it on a global variable?
stars.forEach((star,index) =>{
star.addEventListener('click', ()=>{
stars.forEach((star,idx) =>{
if(idx < index + 1){
star.classList.add('active');
} else {
star.classList.remove('active');
}
console.log(index); // this is working
});
});
});
console.log(index); // this is NOT working
Please check thanks!
First of all, this doesn't seems to be a good idea to do but here you go:
var globalIdx = -1
function fnc() {
var functionIdx = -1
stars.forEach((star,index) =>{
star.addEventListener('click', ()=>{
stars.forEach((star,idx) =>{
if(idx < index + 1){
star.classList.add('active');
} else {
star.classList.remove('active');
}
console.log(index); // this is working
globalIdx = index;
functionIdx = index;
});
});
});
console.log(index); // will not work
console.log(globalIdx); // will work
console.log(functionIdx); // will work
}
console.log(globalIdx); // will work
console.log(functionIdx); // will not work
Just pick one between functionIdx and globalIdx based on what you need.
Hope this helps :)