Stefano
Stefano

Reputation: 178

What is the reason why JS push objects by reference?

What is the reason why Javascript push objects by reference and not by value?

And why this behavior is only for objects and not also for built-in primitives types?

For example:

let x = {a: 10, b: 100 }
let ar = [];

ar.push(x);
x.a = 9;
console.log(ar[0].a); // This print 9, not 10

I think an answer to this question is useful to understand some deep functions about this language.

Thanks in advance.

Upvotes: 0

Views: 132

Answers (1)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Everything in JavaScript is passed by value...

But, those values can be a reference value.

The different seems subtle, but its very important.

For example, if you have a function:

function nukeArray(a) {
  a = [];
}

Then, when you call it, a will receive a value that happens to be a reference. That value is immediately discarded and a is assigned a new reference.

If a was a pure reference, then changing a would also change the value of its caller.

In a language like C you can easily pass a reference -- change the reference -- then the caller's value will be changed as well.

#include <stdio.h>
#include <stdlib.h>

void t(char **t) {
    *t = malloc(50);
}

int main() {
    char *tmp;
    printf("pre: %p\n", tmp);
    t(&tmp);
    printf("post: %p\n", tmp);
}

Upvotes: 3

Related Questions