When are variables evaluated when passing them into functions?

66 views Asked by At

This is probably a simple question, but I would really like to know the answer.

Are the arguments passed into a function calculated once and set as local variables or are they calculated every time they're used inside the function?

For example:

When you write a forLoop, you should set a variable that finds the object using the iteration:

  for(var i = 0; i < objects.length; i++) {
     var obj = objects[i];
     obj.title = "title";
     obj.description = "description";
  }

If you don't set the obj variable then the operation for finding the object will be run more than once:

  for(var i = 0; i < objects.length; i++) {
     objects[i].title = "title";
     objects[i].description = "description";
  }

So far I've learnt that this is bad (although I'm guessing the performance difference in modern browsers is almost unnoticeable).

My question is, if you wrapped the modifying methods in a function and passed objects[i] to the function, would objects[i] be calculated once and set as the local variable obj in the function or would it calculate it every time obj is called?

What is a better practice, code A or code B?

Code A:

   function modify(obj) {
      obj.title = "title";
      obj.description = "description";
   }

   for (var i = 0; i < objects.length; i++) {
      modify(objects[i]);
   }

Code B:

   function modify(obj) {
      obj.title = "title";
      obj.description = "description";
   }

   for (var i = 0; i < objects.length; i++) {
      var obj = objects[i];
      modify(obj);
   }

Update: This question is similar but different to this SO question because it simply questions when the value is calculated rather than which value is passed.

1

There are 1 answers

1
Scimonster On BEST ANSWER

My question is, if you wrapped the modifying methods in a function and passed objects[i] to the function, would objects[i] be calculated once and set as the local variable obj in the function?

Yes. Once the value is passed, it's passed. It doesn't recompile the argument each time.

Therefore, code A will be "better", but i really doubt it makes much of a difference at all....