1

What are the advantages/disadvantages in terms of memory management of the following?

  1. Assigning to a variable then passing it to a function
const a = {foo: 'bar'}; // won't be reused anywhere else, for readability
myFunc(a);
  1. Passing directly to a function
myFunc({foo: 'bar'});
Mico
  • 413
  • 1
  • 6
  • 15
  • 2
    Read passing [reference vs value](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – Cray Apr 05 '19 at 06:20
  • Why would you want to create a variable if it isn't being used anywhere else, or helping in readability at least? – 31piy Apr 05 '19 at 06:33
  • @Cray: Either way it will be passed by ref. –  Apr 05 '19 at 06:34

2 Answers2

0

The first and second code have absolutely no difference between them (unless you also need to use a later in your code) in the way the variable is passed.

The are only 2 cases in which the first might be preferred over the second.

  1. You need to use the variable elsewhere
  2. The variable declaration is too long and you want to split it in two lines or you are using a complex algorithm and want to give a name to each step for readability.
nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

It depends on the implementation of the JavaScript engine. One engine might allocate memory for the variable in the first example and not allocate memory in the directly-passed example, while another implementation might be smart enough to compile the code in such a way that it makes the first example not allocate memory for a variable and thus leaves the first example behaving as the directly-passed example.

I don't know enough about the specific engines to tell you what each one does specifically. You'd have to take a look at each JS engine (or ask authors of each) to get a more conclusive answer.

trusktr
  • 44,284
  • 53
  • 191
  • 263