0

Hello I have some problem understanding the following code related to node.js.

var config = {
    local: {
        mode: 'local',
        port: 3000
    },
    staging: {
        mode: 'staging',
        port: 4000
    },
    production: {
        mode: 'production',
        port: 5000
    }
}
module.exports = function(mode) {
    return config[mode || process.argv[2] || 'local'] || config.local;
}

I cannot understand

return config[mode || process.argv[2] || 'local'] || config.local;

this part. What and how will the OR operator work and return.

Cœur
  • 37,241
  • 25
  • 195
  • 267
theadnangondal
  • 1,546
  • 3
  • 14
  • 28

2 Answers2

0

It is equivalent to:

var r;

if(mode && config[mode]) {
    r = config[mode];
} else if(process.argv[2] && config[process.argv[2]]) {
    r = config[process.argv[2]];
} else if(config['local']) {
    r = config['local'];
} else {
    r = config.local;
}
return r;

Note that config['local'] and config.local would return the same value, so the last part (|| config.local) is useless.

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
0
return config[mode || process.argv[2] || 'local'] || config.local;

EDIT: In the above code everything within the enclosing square bracket will be evaluated prior to attempting to access config[key].

nham
  • 161
  • 5
  • thanks ... it is working like that so I think this is correct. don't know why someone gave you a negative one vote... – theadnangondal Oct 07 '16 at 19:30
  • I suspect it was downvoted because it is incorrect. The key expression is evaluated and a single lookup into `config` is performed. The equivalent is: `var temp = mode || process.argv[2] || 'local'; return config[temp] || config.local;` – cartant Oct 08 '16 at 01:29