What is the point of passing an object into a function?

It seems that whether or not I pass an object into a function as a parameter, the function can alter the object outside of the function’s scope.

not passing it into a function:

var theObject = {
  number: 1
}

function changeObject() {
  theObject.number = 2;
}

changeObject();

console.log(theObject) // number = 2

passing it into a function:

var theObject = {
  number: 1
}

function changeObject(theObject) {
  theObject.number = 2;
}

changeObject(theObject);


console.log(theObject) // still number = 2

Is there a meaningful difference here? In what situations should I pass an object in?

In this example, yes, the function can alter theObject without being passed into the function because it is a global variable as far as the function is concerned.

1 Like

In this exact case, not really. But as bbsmooth points out, global variables are a bad thing. Also, there is a design concept of the “pure function” that a function should only be dependent on the things passed into it and should have not side effects - changing a variable outside of its scope is a side effect. And some would prefer to use “immutable” practices where we don’t alter the object passed in but create a new one and return it. But this is still on your learning path, so baby steps.

But you are right to point out that it seems a little bit odd in this exact case. But imagine a situation where you wanted to be able to pass in different objects. What if you had an array of 100 objects and you wanted to change every object’s property to 2. Would you write 100 functions, the first changes theArray[0].number =2 and on and on? Or you could write a function that takes in the object and use that in a for loop. (Or for more advanced, you could do it in one line with a forEach or map method.

2 Likes

Well, there is at least one difference, you can’t reassign the actual object with the parameter, only the properties.

let user = {
  name: 'John'
}
function changeUserByParam(user) {
  user = {}
}

changeUserByParam(user)
console.log(user); // { name: 'John' }
function changeUserByGlobal() {
  user = {}
}

changeUserByGlobal(user)
console.log(user); // {}

Giving the function parameters can also help document its usage (clearer signature) and potentially guide the correct invocation.

1 Like

Thanks for all of the help. I think the reason that is most convincing to me at this stage of learning javascript is a clearer function signature! I will have to look up the idea of a “pure function.”