0

My Code It Does Not Work. I want to Sum of Numbers that the user gives in arguments.

So I use here Argument Object but am unable to fetch what is the mistake.

    // The Argument Object 
function myFunc()
{
    console.log("You give Total Numbers : "+arguments.length);
    let sum = 0;

    console.log("Sum is : ");
    arguments.forEach(element => {
        sum += element;
    });


    console.log(sum);
}

myFunc(10,20);
myFunc(10,20,30);
myFunc(10,20,30,40);
2

3 Answers 3

1

You could try this solution:

/**
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
 *
 * @param  {array} args ...args is the rest parameters. It contains all the arguments passed to the function.
 */
function myFunc (...args) {
  console.log(`You give Total Numbers : ${args.length}`);
  /**
   * Reduce is a built-in array method that applies a function against an accumulator and each element
   * in the array (from left to right) to reduce it to a single value.
   *
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
   */
  const sum = args.reduce((acc, curr) => acc + curr, 0);
  console.log('Sum is :', sum);
};

myFunc(10, 20);
myFunc(10, 20, 30);
myFunc(10, 20, 30, 40);

Output

You give Total Numbers : 2
Sum is : 30
You give Total Numbers : 3
Sum is : 60
You give Total Numbers : 4
Sum is : 100
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

function myFunc(...arguments)
{
    console.log("You give Total Numbers : "+arguments.length);

    console.log("Sum is : ");
     let sum = 0;
    arguments.forEach(element => {
        sum += element;
    });


    console.log(sum);
}

1 Comment

I suggest you name it something other than arguments since it is not allowed as an identifier in regular functions in strict mode. A common practice is to name it args.
0

try this :

function myFunc() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
}
console.log(
    `
    Total Number : ${arguments.length}
    Sum : ${sum}
    `
);

}

myFunc(10 , 20 , 30 , 40);

out put like this :

Total Number : 4
Sum : 100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.