Search code examples
javascriptarraysloopssumreturn

JavaScript sum function


I have stacked in the sum of an array. The code is bellow

function User(name,email) {
        this.name = name;
        this.email = email;
        this.cartAmount = [];
        this.total = 0;
}
User.prototype = {
        constructor: User,

        addCart: function(mrp){
            this.cartAmount.push(mrp);
        },

        changeEmail: function(newmail){
            this.email = newmail;
        },

        showCart: function() {
            var cart = this.cartAmount.length >0 ? this.cartAmount.join("tk,") : "No product in the cart";
            return this.name+" has "+cart+" in his cart.";
        },

        intotal: function(){
            for(var n in this.cartAmount){
                this.total += this.cartAmount[n];
                return this.total;
            }
        }
    };
    athar= new User("Athar Jamil", "[email protected]");
    console.log(athar.name);
    athar.changeEmail("[email protected]");
    console.log(athar.email);
    athar.addCart(20);
    athar.addCart(50);
    athar.addCart(80);
    console.log(athar.intotal());

It shows me only 20 as the result of the sum. What is the problem?


Solution

  • You're returning too early, hence your for loop runs only once and returns the first item in the cart.

    Try this instead:

     intotal: function(){
        for(var n in this.cartAmount){
            this.total += this.cartAmount[n];
        }
    
        return this.total;
        }