skip to Main Content

I want to pass a variable to a function and have the function change the value.

I know I can do this as an object but am wondering if there is some way to do this that I haven’t thought of.

This is what I want to do, but it doesn’t work the way I want of course:

function test1(vari) {
    vari = 2;
}
var myvar1 = 1;
test1(myvar1);
console.log(myvar1);

This works, but I don’t really want to make all the variables objects:

function test2(vari) {
    vari.val = 2;
}
var myvar2 = { val: 1 };
test2(myvar2);
console.log(myvar2.val);

This also works, but not an acceptable solution:

function test3(vari) {
    eval(vari + ' = 2;');
}
var myvar3 = 1;
test3('myvar3');
console.log(myvar3);

Is there a better option than these?

Updated

A better example of what I would like to do:

function test5(vari, onblur) {
    document.querySelector('body').innerHTML += `<input id="ctl_${vari}" type="text" value="${vari}">`;
    el = document.getElementById(`ctl_${vari}`);
    el.addEventListener('blur', function(e) {
        vari = e.target.value; //Doesn't update original variable
        onblur(e);
    });
    return el;
}
var myvar5 = 'test';
var ele = test5(
    myvar5,
    function(e) {
        //Could set myvar5 = e.target.value but not wanting to do this for every single field
        console.log(myvar5);
    }
);

4

Answers


  1. This might not be what you are looking for, but maybe try something like:

    function test1(vari) {
        return vari += 2;
    }
    
    var myvar1 = test1(myvar1);
    
    console.log(myvar1);
    
    Login or Signup to reply.
  2. Like already stated in the comments, you cannot pass by reference in JavaScript. All arguments passed to a function are pass by value. This is even the case for objects. Though you can mutate an object passed as argument, you cannot re-assign it (making it pass by value). See: Is JavaScript a pass-by-reference or pass-by-value language? for details.

    What you can do is return multiple values using an array:

    function test(a, b) {
      return [a + b, a - b];
    }
    
    let a = 5, b = 2;
    [a, b] = test(a, b);
    

    The final value for a is 7 and b is 3.

    Note that the semicolon after let a = 5, b = 2; is required, otherwise it’s executed as let a = 5, b = 2[a, b] = test(a, b); Which in this case results in "Uncaught ReferenceError: can’t access lexical declaration ‘b’ before initialization".

    However in your specific scenario you could simply pass the desired value to the onblur function as an argument to avoid myvar5 = e.target.value in every function definition.

    function test5(vari, onblur) {
        document.querySelector('body').innerHTML += `<input id="ctl_${vari}" type="text" value="${vari}">`;
        const el = document.getElementById(`ctl_${vari}`);
        el.addEventListener('blur', function(e) {
            onblur(e, e.target.value);
        });
        return el;
    }
    
    var ele = test5('test', function(e, value) {
        console.log(value);
    });
    
    Login or Signup to reply.
  3. In your case I assume the param vari is a primitive value. Here are some ways to fix it

    • Wrap the value with an object
    • Not use it as a parameter (remove it from the function declaration)

    Primitive values like number and string are passed by value

    Others like object and array are passed by reference

    Here are some examples:

    let primitiveVar = 1;
    
    let function1 = (primitiveParam) => {
      primitiveParam = 3;
    };
    
    //not work for primitive values
    function1(primitiveVar);
    console.log(primitiveVar); //1
    
    //------------------------------------
    
    let primitiveVar2 = 1;
    
    let function2 = (primitiveParam) => {
      return primitiveParam + 3;
    };
    
    //due to primitive value immutability we need to reasign
    primitiveVar2 = function2(primitiveVar2);
    console.log(primitiveVar2); //4
    
    //------------------------------------
    
    let objectVar = {
      val: 1,
    };
    
    let function3 = (objectParam) => {
      //objectParam has the same ref as objectVar
      objectParam.val = 2;
    };
    
    function3(objectVar);
    console.log(objectVar.val); //2
    
    //------------------------------------
    
    let objectVar2 = {
      val: 1,
    };
    
    let function4 = (objectParam) => {
      //objectParam ref is now point to a different object
      objectParam = { val: 3 };
    };
    
    function4(objectVar2);
    console.log(objectVar2.val); //1
    

    Working playground: https://stackblitz.com/edit/vitejs-vite-wx9yak?file=main.js&terminal=dev

    Login or Signup to reply.
  4. In JS, only object element’s are passed by reference.
    So don’t expect to be able to do it with a simple variable.

    However, since all variables belong to the window object,
    you can treat it like that, but it’s the worst idea of ​​the century.

    function fx(varName)
      {
      window[varName]++;
      }
    
    var myVar = 5;
    fx('myVar');
    console.log( myVar ); // 6
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search