1

I think JavaScript users mostly spend their time dealing with Objects. And for objects, we can call by reference as following.

let obj = { }

function f (parameter) { }

f(obj)

(parameter and obj refer to the same object, { })

However, I wonder if there is a way to apply this kind of work to primitive values.

let a = 0

function f (parameter) {
  parameter = parameter + 1
}

f(a)

This won't work cause a and parameter are just different variables.

Is there any way to imitate following code from C?

void f (int* x) {
    *x = *x + 1;
}

int main () {
    int a = 0;
    f(&a);
kwonryul
  • 481
  • 3
  • 10
  • 1
    *And for objects, we can call by reference as following* [JavaScript only has call by value for both primatives AND objects](https://stackoverflow.com/questions/42045586/whats-the-difference-between-a-boolean-as-primitive-and-a-boolean-as-property-o/42045636#42045636). There is no call by reference. – Scott Marcus Jul 04 '20 at 23:25
  • @ScottMarcus The passing of an address of an object is what is meant by reference here. Basically, OP is trying to affect the variable outside the function's scope. – sanitizedUser Jul 04 '20 at 23:35
  • 1
    This looks like a duplicate of https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – ibrahim mahrir Jul 04 '20 at 23:53
  • I think arrays are exceptions in this way: say `a=[1,2,3]; b=a; b.pop();` now a==[1,2]... btw, to overcome that: `b=a.slice()`, and to compare arrays, if `a=[1,2,3]; b=[1,2,3];` a!=b, but `JSON.stringify(a)==JSON.stringify(b)` would return `true`. – iAmOren Jul 05 '20 at 00:30
  • reference in objects and arrays yes. but not sure about int/strings – Karl L Jul 05 '20 at 01:55

0 Answers0