0

In the source code of serve-static npm library I have seen the following line

 options = merge({}, options)

where merge function is from utils-merge library and it has exactly the following body

exports = module.exports = function(a, b){
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};

What is the sense of options = merge({}, options) statement since it just joins options object with an empty object?

zavg
  • 10,351
  • 4
  • 44
  • 67
  • 3
    It initializes `options` to an empty object if `options` is `undefined`or leaves `options` with the same values if it's already there (effectively making a shallow copy, as pointed out by Sirko). – toniedzwiedz Nov 09 '14 at 22:31
  • 4
    Actually it makes a shallow copy of `options`. – Sirko Nov 09 '14 at 22:31
  • Similarly, you will see the `$.extend()` function doing the same thing in nearly all jQuery plugins. – bencripps Nov 09 '14 at 22:36

2 Answers2

1

merge({}, options) creates the new object which has the same attributes as source object (so it is the simplest way to clone JS object). But if you don't pass an empty object as the destination object to merge function or just skip this line, all changes on options object inside serveStatic() function will affect external object what passed to function serveStatic().

Here is the detailed explanation of this nuance of JavaScript language: https://stackoverflow.com/a/3638034/1806421

Community
  • 1
  • 1
Kichrum
  • 607
  • 7
  • 8
1

What is the sense of options = merge({}, options) statement since it just joins options object with an empty object?

To do exactly that. It copies all properties into a new object, where they cannot be modified anymore even if the caller of serveStatic still holds a reference to the options object he passed.

However, avoiding that the caller messes with the object is not the only reason for detaching it. If we read on, we see things like

delete options.setHeaders
options.maxage = options.maxage || options.maxAge || 0
options.root = root

so we also want to avoid messing with the object that was passed to us. Mutating your arguments is an antipattern.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375