This is an old revision of the document!


p5js week 09

Phew! It's been lots of toast over the past eight lessons! We'd better take a lesson to catch up and review what we've learned.

We'll review in two parts: general JavaScript and then p5js.

You can open the console in the browser by pressing F12, selecting “developer's tools” from the menu, or right-clicking to inspect and then choosing the console tab.

Making functions is super important! The basic pattern is like this:

// function functionName (arguments) {
//    stuff you want to do;
//    let aValueYouCalculated = the result of some computation above...
//    return aValueYouCalculated // to get out the value you wanted to compute
// }

// which looks like this real function:

function addTwoThenTimes100 (number) {
  let preNumber = number + 2;
  let finalNumber = preNumber * 100;
  return finalNumber
}

The arguments are the input to the function, and the return statement is the output.

When we wrap up some calculations inside of a function, that's called encapsulation.

We can use many kinds of values in our functions, including numbers, strings (“hi!”), booleans (true or false).

Be careful about what order you do stuff; that's called thinking carefully about your procedure.

We can group data together, also called structuring data, into arrays or objects.

Arrays can tell us how long they are when we use the length method. There are also cool methods like forEach, map, and filter that let us avoid using for-loops.

However, if we want to use a for-loop, we can. Remember the basic pattern of a for-loop:

// for (counter variable; stopping condition; increment) {
//  what you want to do on each loop
// }

// you can use it like this inside a function...

function addCounterToBaseNumber (baseNumber, n) {
  let finalNumber = baseNumber;
  for (let i = 0; i < n; i++) {
    finalNumber = finalNumber + i
  }
  return finalNumber
}
  • p5js-week-09.1656177829.txt.gz
  • Last modified: 3 years ago
  • by renick