0

I'm getting this error

TypeError: Cannot read property 'sum' of undefined

How it fixed?

function calculator(firstNumber) {
    var result = firstNumber;

    function sum() {
    for (let i = 0; i <= arguments.lenght; i++) {
        result += arguments[i];
    }

    return result;
    }

    function dif() {
    for (let i = 0; i <= arguments.lenght; i++) {
        result -= arguments[i];
    }

    return result;
    }
}

var myCalculator = calculator(10);
console.log (myCalculator.sum(2, 3));
console.log (myCalculator.dif(1, 2, 5));

I need to get:

15

2

MrFox
  • 11
  • 1
  • 2
    Your calculator class does not return anything - that is the reason you get the error. Here is an example of the nested functions you are trying to emulate: http://stackoverflow.com/questions/3212477/can-you-write-nested-functions-in-javascript – karthikr Dec 10 '16 at 17:48
  • https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript – epascarello Dec 10 '16 at 17:51
  • A lot wrong with this, starting with the typo: length – Tim Grant Dec 10 '16 at 18:03
  • @KarthikRavindra,@epascarello Thank you! – MrFox Dec 10 '16 at 18:05

1 Answers1

1

You need the length property of arguments, iterate < arguments.length and return an object with the two wanted function.

While you take result as variable, it keeps the value from the former calculation. The result is in the first part 15 and later 7, instead of 2.

function calculator(firstNumber) {

    function sum() {
        for (let i = 0; i < arguments.length; i++) {
            result += arguments[i];
        }
        return result;
    }

    function dif() {
        for (let i = 0; i < arguments.length; i++) {
            result -= arguments[i];
        }
        return result;
    }

    var result = firstNumber;
    return { sum: sum, dif: dif };
}

var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));

If you like to get always the result with firstNumber, you could initialize the result with firstNumber.

function calculator(firstNumber) {

    function sum() {
        var result = firstNumber;
        for (let i = 0; i < arguments.length; i++) {
            result += arguments[i];
        }
        return result;
    }

    function dif() {
        var result = firstNumber;
        for (let i = 0; i < arguments.length; i++) {
            result -= arguments[i];
        }
        return result;
    }

    return { sum: sum, dif: dif };
}

var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392