javascriptcode-structure

Is Javascript LBYL or EAFP?


There are two programming approaches: EAFP (Easier to Ask Forgiveness than Permission) and LBYL (Look Before You Leap). First approach presumes doing something that can cause an exception, then handling this exception and second approach presumes using if statements. So is Javascript EAFP or LBYL?


Solution

  • The top answer to this reddit post sums up my opinion on this pretty well, but I'll give my 2 bits.

    Definitely Look Before You Leap.

    Consider this code.

    const thing = {};
    
    try {
      thing.forestryServices.apply();
    }
    catch (e) {
      console.log(e);
    }
    
    thing.forestryServices = {
      apply: "surprise goombas"
    }
    
    try {
      thing.forestryServices.apply();
    }
    catch (e) {
      console.log(e);
    }
    

    The error returned in both cases is an object of type Error. Trying to recover from those errors would be significantly more difficult than doing the required checks ahead of time to make sure your object is valid for what you're trying to do to it.