DEV Community

Discussion on: Cycles while and for in JS, help me!

Collapse
 
chrisdsaldivar profile image
Chris Saldivar • Edited

Loops are always a bit tricky so I like to show my students three basic rules for loops.

  1. Initialize a loop control variable (Used to start and stop the loop)

  2. Write a test condition (Otherwise how will the loop know when to exit)

  3. Update the loop control variable (Without this we'll have an infinite loop)

I've copied the relevant section of your code below and added comments:

var l = 0;               // 1. Setup the loop control variable

while (l < lineas) {     // 2. The test condition that will start/stop the loop
    yi = 10 * l;
    xf = 10 * (l + 1);
    dibujarLinea(colorcito, 0, yi, xf, 300);
    console.log("Linea " + l)
    l = l + 1;           // 3. Update the loop control variable
} 

A for loop is a control structure that allows us to perform all three steps on a single line. It really doesn't add much more functionality than a while loop does since you can simulate a for loop by writing code that way you did for the first drawing. You can achieve the same results as the code above with the following for loop:

//   1. init      2. test   3. update
for (let l = 0; l < lineas; l++){
    yi = 10 * l;
    xf = 10 * (l + 1);
    dibujarLinea(colorcito, 0, yi, xf, 300);
    console.log("Linea " + l)
} 

I hope this clears things up! Also can I ask where that tutorial is from?

Collapse
 
brendalimon profile image
Brenda Limón

Thanks Chris! You’re a great teacher! It’s a course of Platzi, a YC startup that teaches programming in Spanish is platzi.com if you wanna check it :)
Thanks a lot lot lot a thousand lot! 🤗🤗

Collapse
 
chrisdsaldivar profile image
Chris Saldivar

Glad I could be of help! I'm actually not a teacher, I was an undergrad teaching assistant for 2 years and then a grad assistant for the past 3 semesters. I just quit begin a GA for my last year of grad school because I'm making an online course for learning web development called Let's Learn: Fullstack. However, it's aimed at people that have a familiarity with web development and I'd like for it to be accessible to beginners. So, I'm working on a primer course that covers the fundamentals of web development.

Good luck on your web development journey!

Thread Thread
 
brendalimon profile image
Brenda Limón

When your course is ready let me know! I'll like to take it! :D

Thread Thread
 
chrisdsaldivar profile image
Chris Saldivar

Awesome I'll be sure to!