Greetings

I looked at several sources on the current question, but did not understand something with the answer.

I want to make it so that a variable can be passed to a function by reference (as in C / C ++), and within the variable to work with this reference, for example:

function MyFunc(params) { params.my_data++; } let data = 10; myFunc({ my_data: &data, }); console.log(data); // 11 

Tell me, does JS allow such operations?

    5 answers 5

    What exactly you want in js unrealizable. Primitive types are passed by value, not by reference.

     let a = 0 function foo(a) { // здесь своя локальная a a = 10 } console.log(a) // 0 foo(a) console.log(a) // 0 

    Objects are passed by reference, so as in the answers below you can pass an object as an argument

     let data = { a : 0 } function foo(data) { // хоть здесь опять же локальная переменная data // но передается уже по ссылке data.a = 10 } console.log(data.a) // 0 foo(data) console.log(data.a) // 10 

    Well, no one bothers you to just return values ​​from a function

     function foo(a) { return a + 10 } let a = 0 console.log(a) a = foo(a) console.log(a) 
    • It would be nice to make more code examples in a startup, but my plus catch anyway + - Dmitry Polyanin

    Only if the type of data passed to the function is reference.

     function myFunc(params) { params.data++; } let dataHolder = { data: 10 }; myFunc(dataHolder); console.log(dataHolder); // 11 

    Then you can change the parameter properties inside the function, and these changes will be visible from the outside.

      solved the problem with a crutch:

      pass function as a parameter

       function MyFunc(params) { params.my_data(params.my_data() + 1); } let data = 10; myFunc({ my_data: function(value){ if (value != undefined) data = value; return data; }, }); console.log(data); // 11 

      It works, but it looks very sloppy: (

        By reference in JavaScript, only arrays, objects and functions are transferred. Everything else is copied.

        An object:

         function foo(input) { input.a = 2; console.log(input); console.log(data); // оригинальный объект тоже изменился } let data = {a: 1}; foo(data); 

        Array:

         function foo(input) { input[0] = 100; console.log(input); console.log(data); // оригинальный массив тоже изменился } let data = [1, 2, 3]; foo(data); 

        Function: similar to the object.

          In js (almost) there is no link to a variable by reference. And certainly there is no its transmission by reference. Accordingly, it is impossible to make the desired in reasonable ways.

          Alternatively, you can

          • instead of a variable, use the object field
          • return from the function something that will be handled by the caller
          • pass callback instead of variable