Looping in Javascript
One of the first things that threw me for a loop (hahaha) when I first started programming was loops. I just did not understand it, then I found out there’s different types of loops!! To be completely honest I don’t think I really understood anything when I first started programming but loops were really tricky. In programming, loops are a way to do something repeatedly. For instance, if I somehow become smart enough to build a robot to give my dog some love and affection while I’m busy working, I can do a for
loop.
Breaking down this block of code starting from for
, the for
loop repeats until a specified condition evaluates to false. The let
initializes our counter, as we all know in programming, the count/index starts at 0, so bellyRubs
is equal to 0. The next part is the condition, remember our count starts at 0 so as long as the count from 0 is less than 5, it is true & the code will execute. Next the bellyRubs++
is the increment expression, basically firing off the count. Since I’ve set the condition to less than 5, the loop prints George loves his belly rubbed
5 times and then terminates.
The next type of loop is a do...while
, very similar to a while
loop this statement repeats until the condition evaluates to false. In the following screenshots, I’ve added an if
statement with conditions then using the keywords break
& continue
. The do...while
loop will always run the first loop even though the condition is false.
There’s also for...of
which results in the same functionality as a for
loop but with less code.
The code is deconstructing the array, it’s taking each value in the array and setting it to the variable that I’ve name love
because it’s a variable, it can be named anything but after the of
it must be whatever we’ve the named the variable that is the array, in this case it is giveGeorgieLove
. This method can also be used with a for...in
loop, in the example below I used an object with key value pairs.
It took me a very long time to really understand loops and what they were doing but when it comes to learning and understand code, going through every single part of the code and explaining to myself what it’s purpose was, really helped solidify this concept to me. I really hope this helps any code newbies or future newbies! Happy coding!! You know the rest…..