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;
}
console.log(sum);
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 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.
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.