Select Page

Task of Challenge #05/54

Calculate the sum of numbers from 1 to 24 with a for-loop .

Solution

Explanation

For diversity, another challenge, but a simpler one! But that doesn’t mean you can switch off your brain 😉

We can’t just put the accumulated value of sum inside the loop and print it to the console. It would then end up with 24 print outs.

We have to declare and initialize the variable (and please use let here! You can read about the problems of declaring variables with var, let, and const in the featured article below. I advise you to do so!) outside of the loop in order to print it out afterward.

Declaring the variable inside the loop, then it would be initialized every iteration, instead of holding the actual accumulated value.

Furthermore, if we declared it inside the loop it would be out of our reach when we want to access it outside the loop. This is called a scope, declaring a variable inside a class/function/loop, makes it to a local variable which can’t be accessed from the outside (The article below addresses this in detail).

And this is the console output:

Console Printout of the solution.

Follow me on Instagram and don’t miss the latest Challenge!

https://www.instagram.com/arnold.code/

Be sure to write the code write with let, var and const in JavaScript!

Here are two pre-picked and high quality Medium articles for you.