0

I am trying to write an asynchronous array strict equal function that reports errors how I want it to.

Here's my function:

ArrayStrictEqual = function (arr1, arr2, callback) {
    var arr2s = arr2.sort();
    var eq = true;
    try {
        arr1.sort().forEach(function (item, index, array) {
            if(!(_.isEqual(arr2s[index], item))) {
                throw new Error(arr1 + " is not strictly equal to " + arr2);
            }
        });
    }
    catch (err) {
        if (err) eq = false;
    }
    finally {
        callback(err, eq);
    }
};

But, when I run this, it says, Uncaught ReferenceError: err is not defined.

I was going to initialize err to null before the try-catch. But this doesn't seem like the right thing to do. But, I'm not sure what the right thing to do is. Should I be going about this in a completely different way (i.e. not try-catch)?

toshiomagic
  • 1,335
  • 1
  • 12
  • 39

1 Answers1

0

err is only in scope inside the catch statement (see Why do catch clauses have their own lexical environment? for technical details).

You could simply do

try {
    …
    callback(null, true);
} catch (err) {
    callback(err, false);
}

though that might not exactly be what you want, as it calls callback again when the first callback() throws. To avoid that, we'd need try-catch-else like in Python, in JS you need an additional boolean flag for this.

However, throwing an error to break from a forEach iteration is just a horrible practice. Don't do this. Use .every() instead, it does exactly what you really want. Also, you might consider avoiding the mutation of the compared arrays, copy them before sorting.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375