I have a piece of code where I need to assign a value to a variable, but base on condition, it could take other values. It can be done in multiple ways, but need to know which would be preferred in terms of optimization.
1. Assigning the default value in the last else
if (deviceInfo.pop) {
this.forms = getPopFormModel();
this.formMappings = getPopFormMapping(deviceInfo.wlMacs);
} else if (deviceInfo.mode === CONST.MODES.CN) {
this.forms = getCnFormModel();
this.formMappings = getCnFormMapping(deviceInfo.wlMacs);
} else {
this.forms = getDnFormModel();
this.formMappings = getDnFormMapping(deviceInfo.wlMacs);
}
2. Assigning default before checking for conditions
this.forms = getDnFormModel();
this.formMappings = getDnFormMapping(deviceInfo.wlMacs);
if (deviceInfo.pop) {
this.forms = getPopFormModel();
this.formMappings = getPopFormMapping(deviceInfo.wlMacs);
} else if (deviceInfo.mode === CONST.MODES.CN) {
this.forms = getCnFormModel();
this.formMappings = getCnFormMapping(deviceInfo.wlMacs);
}
It looks like assigning 1st version would be better since there is no chance of calling two functions. Would be helpful if someone can point to any references supporting the answer as well.
PS: Also consider a scenario where the called functions are simply returning objects without any additional functionality.
Thanks