Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
How to get the value of 'index' and put it on a global variable?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 :)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!