0

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;
}
10
  • 1
    The first code returns the first matched service, the second returns the last matched service. It's not obvious what "NOT WORKING" means. They are equivalent and most likely identical. Commented Jan 18, 2016 at 3:28
  • Use filter. getSelectedService: function(serviceId) { serviceId = parseInt(serviceId); var service = servicesData.filter(service => service.id === serviceId); return service.length ? service[0] : {}; } Commented Jan 18, 2016 at 3:29
  • @Tushar why would one prefer your suggestion over the first code example? And as soon as you use ES2015 - why not use Array.prototype.find()? Commented Jan 18, 2016 at 3:30
  • 1
    jsfiddle.net/q4s85vfm --- your first code works for sure. Commented Jan 18, 2016 at 3:33
  • 1
    @zerkms you're right. I looked elsewhere and found the problem Commented Jan 18, 2016 at 3:37

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

@methuselah - There's no fundamental reason a while loop is better than a for loop for this purpose. The two can be used fairly interchangeably. You can break out of a for loop with break or return just fine.
I agree, I just gave an answer different from the solutions he tried.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.