Dinamo788 Dinamo788 - 1 year ago 118
Javascript Question

Beginner Challenge: Sum all even numbers 1-1000. Is my rationale wrong or just my code?

I just began coding the other day and I'm going through coding dojo's free beginner algorithm course. I had no trouble with the intro lesson predicting outputs, but now I am writing code my thoughts don't seem to translate well.

The task is to write a function that would get the sum of all the even numbers from 1 to 1000. They mentioned I could use the modulus operator, but I think that operator is a little contrived. Instead I figured it easier and more efficient to run a For loop, starting at 0 and adding 2 each loop. After each loop the new number would be added to the previous which would be the current sum variable. I have attached my attempted solution:
My attempted reasoning

Unfortunately this only freezes my browser until I stop script (I guess it's on an infinite loop). Most of the previous lesson work involved outputs using console.log() and I'm not even sure why I can't use it instead of the return operator. Can tell me if my way of going about solving the problem is valid or not and if it is, what's wrong with the code. And if it's not, where the flaw is in my logic. I have included the suggested solution below. Suggested solution

Thanks all

Also if you have time, why does a semicolon after the If operator change the answer so much? I still don't know the hard rules of semicolon use.

Edit: Thanks guys, what a great community!

Answer Source

Your for loop is incorrect. You have

for(var x=2; x!=1000; x+2)

Where you should do

for(var x=2; x<=1000; x = x+2)

Currently, your loop never updates x so it has the same value all the time. Statement 3 in the for loop is executed as it is so your code just executes x+2 which is just some number. The code I suggested above updates x to be equal to x+2.

Your condition terminates the loop once x is equal to 1000 so 1000 is not added to the sum. You need to either break the loop when x is equal to 1002 or better use


Putting a semi-colon after the if condition means that you want to do nothing if that condition is satisfied. If you don't put a "{" after the if then only one statement following the if statement is executed when your condition is satisfied. When you put a semi-colon, then you execute an empty statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download