3

Today I learned that if for example I have an object:

var foo = {a: 1, b: { ... }}

And I pass it to a function:

function test(foo) {
  foo.b
}

It has to load the whole foo object into the function’s scope to access the b property, which increases the memory consumption.

The advice in the book is to always pass only what you need instead:

function test(b) {
   b
 }

 test(foo.b)

My question if that's is true? and why? the object is passed by reference.

undefined
  • 6,366
  • 12
  • 46
  • 90
  • While passing an object into a function a variable created that references the passed object not the objects address itself. So in a function if you assign it sth like this `foo = {}` it won't effect the passed object you only changed the reference of the scoped variable. – Eldar Dec 26 '19 at 10:30
  • But I can mutate the object properties. – undefined Dec 26 '19 at 10:46
  • 1
    Yes because your variable points to original object. So you have 2 variables `foo` which is original and the one generated for function that points to original – Eldar Dec 26 '19 at 10:48
  • And both points to the same address in memory – undefined Dec 26 '19 at 10:50
  • That is because it will create a new environment record for the function scope which pretty much copies over the values. Reference: https://tc39.es/ecma262/#sec-function-environment-records – scripton Dec 26 '19 at 10:54
  • @scripton but the record is more or less equal in both cases. Also the spec does not mandate a memory model. – Jonas Wilms Dec 26 '19 at 11:00
  • https://stackoverflow.com/questions/16880418/javascript-pass-object-as-reference, duplicated reference of same object is passed, so you can mutate the object but not replace it. – Akash Shrivastava Dec 26 '19 at 11:06

2 Answers2

6

It has to load the whole foo object into the function’s scope to access the b property, which increases the memory consumption.

This is just wrong. As you said

the object is passed by reference.

Thus in both cases a reference gets passed, which will consume the same memory (if it does at all).

The advice in the book is to always pass only what you need instead

That makes sense as a good practice for clean design.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Nope and here's proof.

const foo = {a: 1, b: 'bar'}

function printB(obj){
    console.log(obj.b)
    setTimeout(() =>console.log(obj.b),1000)
}

// pitfall changing a object inside a function
function editB(obj){
    obj.b = `I'm just writing something to an object`
}

printB(foo)
// prints bar
editB(foo)
// after one second it prints 'I'm just writing something to an object'
fubar
  • 383
  • 2
  • 11
  • watch out for editing an object inside a function because it WILL impact other functions using this object --> Eliminated by passing a value so its clearly the better option – fubar Dec 26 '19 at 14:09