0

Im working on a project, and in an attempt to shorten the amount of code I wrote a function to call all of them at once. It looks something like this function Function(peram1) {peram1 = peram1 += 5}; And I call it like so Function(someVariable) My issue is that I need to change the variable someVariable from inside the function, even though the value of peram1 is simply just the value of someVariable, but cant directly change it. I call multiple of these functions, so I cant simply just call the actual variable name from within.

var someVariable = 5;
var someSeperateVariable = 8;

function Function(peram1) {
    peram1 = peram1 += 5;
};

Function(someVariable);
Function(someSeperateVariable);
console.log(someVariable, someSeperateVariable);

3 Answers3

0

Consider returning a value from Function

var peram1 = Function(Peram1);

Another option in case peram1 is not an object - is to wrap peram1 with an object:

var objContainPeram1 = {    peram1: peram1 }

Function (objContainPeram1) {
     objContainPeram1.peram1 = objContainPeram1.peram1 + 5  
}
chenop
  • 4,743
  • 4
  • 41
  • 65
0

You can use an object to store variables, pass property name and object to function

var obj = {someVariable:5, someSeparateVariable:8};

function fn(prop, obj) {
    obj[prop] += 5;
};

fn("someVariable", obj);
fn("someSeparateVariable", obj);
console.log(obj.someVariable, obj.someSeparateVariable);
guest271314
  • 1
  • 15
  • 104
  • 177
0

Another solution would be to wrap your code in a function to create a closure:

function closure() {

    var someVariable = 5;
    var someSeperateVariable = 8;

    function foo() {
        someVariable += 5;
    };

    console.log(someVariable)
    foo()
    console.log(someVariable)

}

closure()
Gillespie
  • 5,780
  • 3
  • 32
  • 54