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

168
Views
Define an array just once and change it without defining it again in JavaScript

I want to define an array in a line of the program, for example, as follows:

var a = [2,5];
//In the next steps, I want to increase the array elements as follows:
a[0] += 2;
a[1] += 2;
//And I want the array to increase intermittently at the output of the program, as follows:
a = [4,7]
a = [6,9]
a = [8,11]
//....

But in reality this does not happen because in the first line of the program, the array is defined again and again.

And the output is always as follows: a = [4,7];

Is there a way to initialize the a array as [2,5] only once?

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

0

There are many ways to do this.

  • This is a very simple way if you want to increase it a fixed number of times:
    let a = [2,5];
    for (let i=0;i<5;i++) {
        a=a.map(element=>element+2);
        console.log(a);
    }
  • Using a nested function/closure as shown in Lonnie Best's answer

  • Or you can also use a generator function:

    function * arrayIncreaser(initialArray, num) {
      let a = initialArray;
      while (true) {
        a = a.map(element=>element+num)
        yield a;
      }
    }
    
    const increaser = arrayIncreaser([2,5],2)
    console.log(increaser.next().value);
    console.log(increaser.next().value);
    console.log(increaser.next().value);
about 4 years ago · Juan Pablo Isaza Report

0

Here, I use a closure. The array is created once and modified each time you call increase():

function createIncreaseFunction()
{
  const a = [2,5];
  function increase()
  {
    a[0] += 2;
    a[1] += 2;
    return a;
  }
  return increase;
}
let increase = createIncreaseFunction();
console.log(increase()); // [4,7]
console.log(increase()); // [6,9]
console.log(increase()); // [8,11]

// increase() modifies the values in the array,
// but the same array is returned each time:
console.log(increase() === increase()); // true

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!