Search code examples
javascriptangularjswebstorm

AngularJS JavaScript for loop warning that will run at most once


Why does WebStorm warn me that my for loop will only run at most once?

if (data[i].name) {
    for (var j = 0; j < data[i].name.length; j++) {
        hobby = $scope.users[data[i].name].hobby;
        sport = $scope.users[data[i].name].sport;
        education = $scope.users[data[i].name].education;
        break;
    }
}

Where is the problem? What am I missing here?


Solution

  • As mentioned in the comments, the loop is only executed once at most since you break the execution after the first iteration.

    However, from looking at the code, you may not need a loop here at all. It seems like all you want to do is check whether the string data[i].name is set, and if so, retrieve some properties based on that, correct?

    If so, remove the loop, as it does not contribute anything to the posted snippet:

    if (data[i].name) {
        hobby = $scope.users[data[i].name].hobby;
        sport = $scope.users[data[i].name].sport;
        education = $scope.users[data[i].name].education;
    }
    

    Assuming that data[i].name is a string, data[i].name.length will only give you the length of the string.