javascriptnode.jsjavascript-objectsself-invoking-function

NodeJS: shorter way to create a conditional property in an object than self-invoked function? (either ES5 or ES6)


Is there a shorter way to express the following? (either ES5 or ES6)

res.cookie('abc', 'xyz', (function(){
            var obj = {maxAge: 900000, httpOnly: true };
            if (process.env.NODE_ENV==="production"){
                obj.secure = true;
            }
            return obj;
        })());

Solution

  • ES6 offers the Object.assign method, which you might be able to use like so:

    var obj = Object.assign(
      {
        maxAge: 900000,
        httpOnly: true,
      },
      process.env.NODE_ENV === "production"
        ? { secure: true }
        : {}
    )
    

    That will ensure that the key secure is not even present in the final object if the environment isn't production. If you're okay with the key being there, but with a value of false, then:

    var obj = {
      maxAge: 900000,
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
    }
    

    will suffice.


    In even newer versions of ECMAScript, you have access to object destructuring using the ... operator. So you could turn the first snippet into a more concise version:

    var obj = {
      maxAge: 900000,
      httpOnly: true,
      ...process.env.NODE_ENV === "production"
        ? { secure: true }
        : {},
    }