PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] What is the reason why JS push objects by reference?

 July 06, 2022     arrays, javascript, pass-by-reference, reference     No comments   

Issue

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.


Solution

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);
}


Answered By - Jeremy J Starcher
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing