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

232
Views
How do I make changes to a local variable without changing the global variable in javascript?
var i = 100;

function gamePlay() {
       
    while(i >= 0) {
        if (i>0) {
            console.log(i);}
        else{console.log(**i+1**);}
        i--;
    }
}
    

When I increse i by 1 (the part of the code that is bold), I'd like to make that change occur locally. The rest of the code should use global i but the problem is that the change applies globally and the rest of the code stops working when I add 1 to i. This is the case even if I substract 1 before closing the while loop.

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

0

Try this:

var i = 100;

function gamePlay() {
    let i2 = i; // local variable

    while(i2 >= 0) {
        if (i2 > 0) {
            console.log(i2);
        }
        else {
            console.log(i2+1);
        }

        i2--;
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

When you declare variables in a function, they are local to that specific function. But when you declare them outside of the function, they are global and can be used anywhere.

In your case var i = 100 is global and can be used in any function. So you need to declare another variable inside the while block.

about 4 years ago · Juan Pablo Isaza Report

0

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitly by typing the var keyword before the name of the variable.

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!