0

I'm trying to decipher some code and I stumbled upon this:

var disabled = mswDisabledValue === 'true' ? true : false;
var serviceWorkers = JSON.parse("[{\"scope\":\"/\",\"serviceWorkerUrl\":\"/uxsw/scope/root.js\"},{\"scope\":\"/x\",\"serviceWorkerUrl\":\"/uxsw/scope/now_x.js\"},{\"scope\":\"/now\",\"serviceWorkerUrl\":\"/uxsw/scope/now_x.js\"}]");
var SERVICE_WORKER_MANAGER_CONFIG = { disabled, serviceWorkers };

What does the third line mean?

I tried printing SERVICE_WORKER_MANAGER_CONFIG, and it returned an object:

{
  disabled: false,
  serviceWorkers: [{
      scope: '/',
      serviceWorkerUrl: '/uxsw/scope/root.js'
    },
    {
      scope: '/x',
      serviceWorkerUrl: '/uxsw/scope/now_x.js'
    },
    {
      scope: '/now',
      serviceWorkerUrl: '/uxsw/scope/now_x.js'
    }
  ]
}

Seems like I can declare an object using variables instead of key/value pairs, but I haven't found this documented anywhere. Is this the correct usage of JavaScript?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 6
    Yes, this is valid javascript. It's a shorthand for `{ disabled: disabled, serviceWorkers: serviceWorkers }`. Saves you some keystrokes. – Sergio Tulentsev Dec 23 '22 at 14:44
  • 3
    While you're learning from this code, note that the **first** line should be `var disabled = mswDisabledValue === 'true';` — the `? :` operator is completely unnecessary there, because the `===` comparison will result in `true` or `false`. – Pointy Dec 23 '22 at 14:45
  • 1
    It is described in the JavaScript documentation of [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). – axiac Dec 23 '22 at 19:07

1 Answers1

1

The line

var SERVICE_WORKER_MANAGER_CONFIG = {disabled, serviceWorkers};

is a valid javascript object initializer. It is also called "Object literal syntax" and it is used as a shorthand for initializing JSON objects. It is identical to calling:

var SERVICE_WORKER_MANAGER_CONFIG = {disabled : disabled, serviceWorkers : serviceWorkers};

More information and examples can be found on MDN.

Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27