Loop Explanation | How does it work

Hi, everyone. Nice to meet you all! I’m new here. Just trying to figure something out.

So, I’m not actually the type of logical guy, I’m more into visualizing/imaging than analyzing. That is why I just had trouble understanding this loop. I already know the basics, and now I just had this thought ‘Why not go further?’ And so I did, thinking it could be fun and exciting, until I came across with this code that almost got my brain broke. I just want an explanation on how did this work?

It’s called “Displaying the Sum of Natural Numbers.”

let sum = 0;

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


Output: 55

How in the world did it got a 55? Where did it came from? I need someone to do/explain the math, from the top to bottom.

I don’t like logic, but I’m ultra willing to learn. I’m actually doing a self-taught learning. So, yeah, things like this is expected to happen. But I’m up for the challenge!

(I’ve got two more question after this)

Hi @Adam22

Welcome to FCC

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

Thanks, mate. Appreciate it. I’ll make sure to do that next time.

This is a simple for loop which increments the value of i from 1 to 10 incl.

On each iteration of the loop, the value of i is added to sum:
0 + 1 + 2 + 3 … + 10 = 55

1 Like

Wow! That’s just it? I didn’t thought about that. Man that was too easy. Really cool. Thanks mate! I got it now, really, thank you.

I got another one

var numbers = [1, 4, 44, 64, 55, 24, 32, 55, 19, 17, 74, 22, 23];
var max = 0;

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];

console.log(max); // 74

how did this happen?

It’s another simple loop, but it iterates all of the elements in the numbers array. It checks each value in turn to see if it’s larger than all previous values and this way it finds the max value in the array.

This is bread and butter Javascript stuff, which you could pick up quite quickly if you follow a decent tutorial.

Have you tried working through the FCC Javascript Algorithms and Data Structures course? It would teach you this and much, much more besides!