News for hackers. Stuff that matters.
Re:Use labels to break ifs in JavaScript by delinka on Wednesday August 07, 2013 @09:42AM (#6172733)
EDIT: That this JS feature lets the developer break an outer scope from an inner scope is pretty awesome. I should ponder whether I can conjure this in C...

====

I'm with you. Now, take the case of a function that can return "early" - because it hit a condition that prevented it doing its job, or because it finished early on in its code. I've recently been requiring such functionality in places that have accumulated resources which should be released or otherwise tidied before returning. My fellow co-workers have been using goto, and at the label freeing the resources. My solution is to use 'while' and break (you could certainly use 'for' instead):

  struct some_object *o = some_object_create(); // maybe you alloc here, and set properties
  OtherType *result = NULL;
  
  while(true) {
    if (cond_based_on_args) {
      result = OtherTypeCreate(...);
    }
    if (!result) break;
    if (OtherTypeGetValue(result) != kCorrectValue) {
        OtherTypeFree(result);
        result = NULL;
        break;
    }
    
    /* Other work to do with 'result' */
    
    break; // never let it run again
  }

  some_object_free(o);
  
  return r;
This code is a bit contrived, but I think it illustrates the idea.
Re:Use labels to break ifs in JavaScript by dclowd9901 on Wednesday August 07, 2013 @09:06PM (#6176764)
I would use Promises to handle the situation of "returning early." Essentially, you create recursive function, and execute it in a setInterval (don't forget to bind the scope if you're doing class references!). Manage state outside the scope of the function and create a deferred object outside the scope as well. When it's done, resolve the promise and kill the .

Elsewhere, use the resident "when" function to capture the resolved state. This helps create a very secular structure of code where each method is purposeful.

Re:Use labels to break ifs in JavaScript by rainforest on Wednesday August 07, 2013 @10:44AM (#6173157)
One debatable potential improvement to your alternative could be to use the `do { } while(false)` idiom - that removes the need to preserve the terminating break (and the chance of it being accidentally removed).