Shervin Rafiie
Shervin Rafiie

Reputation: 1

Creating a for loop in javascript

I am trying to make this for loop work, my assignment is;

We want to write a function summation that will find the sum of all the values from 1 to (and including) n. The value n is passed into our function.

Similar to the for loop above, you can initialize some value i to start at 1. The value should reach n but never exceed it.

My code is;

function summation(n) {
  let sum = 0;

  for (let i = 1; i <= n; i++) {
    sum = sum + n;
  }

  return sum + i;
}

module.exports = summation;

Getting these errors;

summation
    1) should sum up to 2
    2) should sum up to 3
    3) should sum up to 4


  0 passing (5ms)
  3 failing

  1) summation
       should sum up to 2:
     ReferenceError: i is not defined
      at summation (summation.js:8:14)
      at Context.<anonymous> (test/test.js:6:22)
      at processImmediate (internal/timers.js:461:21)


  2) summation
       should sum up to 3:
       ReferenceError: i is not defined
       at summation (summation.js:8:14)
       at Context.<anonymous> (test/test.js:9:22)
       at processImmediate (internal/timers.js:461:21)

   3) summation
       should sum up to 4:
       ReferenceError: i is not defined
       at summation (summation.js:8:14)
       at Context.<anonymous> (test/test.js:12:22)
       at processImmediate (internal/timers.js:461:21)

Upvotes: 0

Views: 37

Answers (1)

Barmar
Barmar

Reputation: 780994

You should be adding i to sum inside the loop, not after the loop is done. You can't access i after the loop, because let i declares the variable to be local to the loop.

function summation(n) {
  let sum = 0;

  for (let i = 1; i <= n; i++) {
    sum = sum + i;
  }

  return sum;
}

console.log(summation(2));
console.log(summation(3));
console.log(summation(4));

Upvotes: 1

Related Questions