Andrew Lyndem Andrew Lyndem - 9 months ago 20
Javascript Question

How to find the sum of all numbers between 1 and N using JavaScript

I'm trying to find a way to calculate the sum of all numbers between 1 to N using JavaScript. The following is the code I have tried so far but it doesn't seem to work.

function numberSum(N) {
var total = 0;
for(var i = 1; i <= N; i++){
total += i;
return total;

I have tried using jslint and other validators online to check if I might have missed something but that doesn't seem to help me find the reason for the code not working either. Is there something that I'm missing above that's preventing the script from executing the addition??


Your code is fine.

Keep it simple:

var res = (n * (n+1)) / 2;