Why run time error on undefined?

I’m trying to understand why this works.

var twoSum = function(nums, target) {
    let result = nums.reduce((answers, value, index, src) =>{
           let pair = src.indexOf(target-value);
           return (answers.length < 2) && (pair != -1) && (pair != index) ? [...answers, index]        :answers;
    },[]);
    return result;
};

But this gives me a runtime error that answers is undefined.

var twoSum = function(nums, target) {
    let result = nums.reduce((answers, value, index, src) =>{
           if(answers.length < 2) {
           let pair = src.indexOf(target-value);
           return  (pair != -1) && (pair != index) ? [...answers, index]   :answers;
    },[]);
      } else {
       return answers;
    }
    return result;
};

It seems like the scope of answers should be the same in both cases but obviously is not.

Your else clause is outside of the scope of the callback function for the reduce.

Thanks for some reasons I assumed the issue was in the if clause.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.