methuselah
methuselah

Reputation: 13206

Correct way to break out of if statement within for loop

What is the correct way of breaking out of a nested if statement/for loop? I have tried the following approach but the preferred approach does not work:

service.js - NOT WORKING but better because it breaks out as soon as a match is found

    getSelectedService: function(serviceId) {
        serviceId = parseInt(serviceId);
        for(i=0;i<servicesData.length;i++) {
            if(servicesData[i].id === serviceId) {
                var service = servicesData[i];
                return service;
            }
        }
    }

services.js - WORKING but not good as it loops through everything even when a match is found

getSelectedService: function(serviceId) {
    serviceId = parseInt(serviceId);
    servicesData.forEach(function(service) {
        if(service.id === serviceId) {
            var selectedService = service;                  
        }
    });
    return selectedService;
}

Upvotes: 0

Views: 5528

Answers (1)

Corentin Bruneau
Corentin Bruneau

Reputation: 146

If you want to stop on the first match, you shoud use a while loop.

var keepGoing = true;
var i = 0;
var service;

while( keepGoing && i < servicesData.length ) {
    if( servicesData[i].id === serviceId ) {
        service = servicesData[i];
        keepGoing = false;
    } else {
        i++;
    }
}

return service;

Upvotes: 1

Related Questions