Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Creating a local variable whose scope does not extend beyond the current function does not incur any cost compared to not creating one and writing the expression directly as the argument to the function. In fact, nothing tells you that writing <code>someFunction(x*2)</code> won't be transformed to code that binds a variable to the result of <code>x*2</code> internally by the javascript compiler - indeed, many compilers and JITs use SSA as one of their intermediate representations, in which form a variable is <em>always</em> bound to the result of every sub expression. See the relevant <a href="http://en.wikipedia.org/wiki/Static_single_assignment_form" rel="nofollow">Wikipedia entry</a>. Whether in a closure or not makes no difference.</p> <p>The only two relevant questions that should concern you to make a choice between introducing a new variable and writing the expression as an argument directly are:</p> <ol> <li><p><strong>Readability:</strong> does naming the result of the expression make clearer what the expression is computing;</p></li> <li><p><strong>Cost of evaluating the expression:</strong> if you will be writing the expression more than once, then binding a variable to the result will you to reuse avoid recomputing the result everytime. This is <em>only</em> relevant if your expression is expected to take a long time to compute.</p></li> </ol> <p>If you only need to write the expression once inside a function definition then binding a variable to the result may well make the result live in memory longer than is strictly necessary, but this is nearly always completely irrelevant: most function calls are very short lived, in many cases the result does not take up much memory and the memory allocated on the stack will be reclaimed upon function exit and the memory allocated on the heap will be reclaimed by garbage collector soon thereafter.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload