0

I have a question about arguments passing in Javascript, as I know that, for primitive data types, when passing through a function, they got copied by value.

Haw about the reference data types?

As an example, see this code:

var person3 = new Object();
setName(person3);
console.log(person3)
function setName(obj){
  obj.Name = "remon"
}

For whom said that it is duplicate, it is not because I am asking the question from memory perspective and I am new in learning programming and the answers to that questions is so advanced for me.

bruno
  • 2,213
  • 1
  • 19
  • 31
  • Not much to qualify as an answer, so I'll just comment. Your instinct is right. referenced values get passed by reference, primitives get passed by value. – zfrisch Jan 08 '19 at 19:16
  • Possibly a duplicate of https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – antonku Jan 08 '19 at 19:17
  • Possible duplicate of [Javascript confusion over variables defined by reference vs value](https://stackoverflow.com/questions/9473601/javascript-confusion-over-variables-defined-by-reference-vs-value) – zfrisch Jan 08 '19 at 19:18
  • 1
    reference get passed as reference, so person3.Name will be "remon" – Vishnu Jan 08 '19 at 19:18
  • for whom said that it is duplicate it is not because I am asking the question from memory perspective and i am new in learning programming and the answers to that questions is so advanced for me –  Jan 08 '19 at 19:20
  • @MinaShaker What do you mean by "memory perspective", and what language in the referenced answers do you not understand? – Bergi Jan 08 '19 at 19:26
  • I mean where it is got stored is it on the heap or in the stack when passing a object to a function –  Jan 08 '19 at 19:28
  • 1
    Docs on data types https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures – Valery Baranov Jan 08 '19 at 19:37
  • @ValeryBaranov thanks of course for your answer but what I want to say is that I know the data types and the difference between them but what I want to know when passing a variable from out side a function and it’s data type is object through a function do it got copied by reference or value –  Jan 08 '19 at 20:08

1 Answers1

0

@MinaShaker well, your experiment shows, that it is copied by reference. We see {Name: 'remon'} in console.

var person3 = new Object();
setName(person3);
console.log(person3)
function setName(obj){
  obj.Name = "remon"
}

And here, if we 'copy' object before sending it to the function we will get {Name: 'simon'}

var person3 = { Name: "simon" };
setName(Object.assign({}, person3));
console.log(person3)
function setName(obj){
  obj.Name = "remon"
}
Valery Baranov
  • 368
  • 3
  • 10