/
p5.js Loops

p5.js Loops

A loop is a control statement that allows us to repeat a code block. Loops contain a conditional which determines how many times the code block is repeated.

There are few different loop types:


For-loop

The for loop loops through a block of code a specified number of times.

 

for([variable declaration], [condition], [increment step]) {

[code block] 

}

for(let i=0; i <= 100; i++) { print(i); }

 

For-In-loop

The for in loop loops through the properties of an object.

 

for([variable declaration], [condition], [increment step]) {

[code block] 

}

let person = {name:"Maik", surname:"Muster"}; let x; for (x in person) { print(x) }

 

While-loop

The while loop cycles through a block of code as long as its specified condition is true.

 

while ([condition]) {

 [code block]
}

let x=0; while(x <= 100) { print(x); x++; }

 

Do-While-loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, it will then repeat the loop as long as the condition is true.

 

do{
} while([condition]);

Exercise

Write a program that creates a line of animated icons on the screen using a loop. Make use of the sin() function to create a simple oscillation.    

Related content

p5.js Programming
p5.js Programming
Read with this
p5.js Variables
p5.js Variables
Read with this
p5.js Introduction
p5.js Introduction
Read with this
p5.js Random Numbers
p5.js Random Numbers
Read with this
p5.js Particle System
p5.js Particle System
Read with this
p5.js WebGL
p5.js WebGL
Read with this