Hacker News new | ask | show | jobs
by alfonsodev 1747 days ago
Agree and it could be easier to read in my opinion if you deal with the exceptions first. For example.

    let v = Number.parseInt("a3", 10);
    try {
        if (Number.isNaN(v)) {
            throw new Error("NaN");
        } else if (v > 3) {
            throw new Error("gt 3");
        }
        v += 1;
    } catch (error) {
        v = 3;
    }
    v += 1;

Or writing a "guard function" that throws ...

    function throwIfNaNorGt3(v) {
        if (Number.isNaN(v)) {
            throw new Error("NaN");
        } else if (v > 3) {
            throw new Error("gt 3");
        }
    }

    let v = Number.parseInt("a3", 10);
    try {
        throwIfNaNorGt3(v);
        v += 1;
    } catch (error) {
        v = 3;
    }
    v += 1;