Ctrl_Alt_Defeat Ctrl_Alt_Defeat - 22 days ago 5
Javascript Question

Javascript switch statement?

I have some code like below:

for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;

if (option == "A") {
$scope.aSelected = true;
break;
}
}

for (var i = 0; i < $scope.Option.length; i++) {

var option = $scope.Option[i].Code;

if (option == "B") {
$scope.bSelected = true;
break;
}
}


Is it possible to right this in a switch statement like below:

for (var i = 0; i < $scope.Option.length; i++) {

var option = $scope.Option[i].Code;

switch (option) {
case "A":
$scope.aSelected = true;
break;
case "B":
$scope.bSelected = true;
break;
default:
console.log('unrecognized option');
}
}


Is this actually incorrect in the switch case because the first option may be A which will break out of the loop and then for example if 'B' was the option in a later position of the collection it would never get bSelected = true;

Answer

It's correct because the BREAK inside of SWITCH will break out of it, not the whole FOR loop, and therefore it will check for B too.