Search code examples
javascriptpass-by-referencepass-by-value

Better way to handle operations with many variables?


I have around 30 values stored as variables:

var a = 1,
    b = 2,
    c = 3,
    ...
    z = 26, 
    aa = 27,
    ab = 28;

that I want to scale. I do so using an array:

array = [a, b, c];
var scale = 5;

for (var i = 0; i < array.length; i++){
    array[i] = array[i] * scale; // Some simple arithmetic
}

To get the new scaled value, I need to reassign my variables.

var a = array[0],
    b = array[1],
    c = array[2],
    ...
    z = array[26], 
    aa = array[27],
    ab = array[28];

This is cumbersome, even if I use destructuring assignment. What is a better way to manage all the information I have?


Solution

  • Using plain variables you won‘t find a smarter way. I‘d suggest to use objects instead as arrays are anonymous because you access the content by index instead of a name:

    let groupA = { 
         a: 1,
         b: 2,
         c: 3
    }
    

    You can then iterate and multiply via

    for (let key in groupA) {
        if (groupA.hasOwnProperty(key) {
             groupA[key] *= 5;
        }
    }   
    

    but you still can access each field individually

    console.log(groupA.a);