Can some please explain this JavaScript for loop from Browserstack?

126 views Asked by At

I'm using BrowserStack to run my test automation - there is a config example on their site to set up 'commonCapabilities'.

I know this is basic JS but what's the use for the double pipe within this for loop?

// Code to support common capabilities
exports.config.multiCapabilities.forEach(function(caps){
  for(var i in exports.config.commonCapabilities) caps[i] = caps[i] || exports.config.commonCapabilities[i];
});

The full config:

https://www.browserstack.com/automate/protractor

exports.config = {
  'seleniumAddress': 'http://hub-cloud.browserstack.com/wd/hub',

  'commonCapabilities': {
    'browserstack.user': 'xxxx',
    'browserstack.key': 'xxxx'
  },

  'multiCapabilities': [{
    'browserName': 'Chrome'
  },{
    'browserName': 'Safari'
  },{
    'browserName': 'Firefox'
  },{
    'browserName': 'IE'
  }]
};

// Code to support common capabilities
exports.config.multiCapabilities.forEach(function(caps){
  for(var i in exports.config.commonCapabilities) caps[i] = caps[i] || exports.config.commonCapabilities[i];
});
2

There are 2 answers

0
bitten On BEST ANSWER

It's an expression that is more easily read like so:

for(var i in exports.config.commonCapabilities) {
  caps[i] = (caps[i] || exports.config.commonCapabilities[i]);
}

Which means return caps[i] if it can be converted to true; otherwise, return exports.config.commonCapabilities[i]. If caps[i] is undefined, as that's a falsey value, it'll set the variable to exports.config.commonCapabilities[i]. It's a way of making sure each is defined, otherwise fallback to some standard config.

0
Kevin Kloet On

this part: caps[i] = caps[i] || exports.config.commonCapabilities[i] basically says if caps[i] is not defined (or null, false, 0, NaN, ""(not a falsey value)) run than caps[i] = exports.config.commonCapabilities[i].

for example:

var x = x || "value"

which has the same functionality as

if(x){/*nothing as it is already assigned*/} else {x = "value"}

If the first value is false, it checks the second value. If it's true, it returns true and if it's false, it returns false. If the first value is true, it always returns true, no matter what the second value is. from here