Print & Log

p5 gives us a print function, which prints whatever we pass into it to the console.

For example, this code:

function setup () {
    createCanvas (400, 400)
    const msg = `Hello RMIT Creative Coding Specialisation!`
    print (msg)
}

... prints Hello RMIT Creative Coding Specialisation! to the console.

function setup () {
    createCanvas (400, 400)
    const result = 77 ** 3
    print (result)
}

... prints 456533 to the console (77 to the power of three).

function setup () {
    createCanvas (400, 400)
    const is_equal = 5 * 7 == 6 * 6 
    print (is_equal)
}

... prints false to the console (because 5 x 7 does not equal 6 x 6).

Passing an object in to print gives a slightly different behaviour:

// declaring variable "mid_point"
let mid_point 

function setup () {
    createCanvas (400, 400)

    // creating a vector object and
    // storing it in mid_point
    mid_point = createVector (width / 2, height / 2)

    // passing the vector object in
    // as an argument to print
    print (mid_point)
}

Some information about the object is output on the console, along with a small triangle:

vector object in the console

Clicking on the small triangle will unfold the object, displaying the object's attributes (data), and methods (behaviour).

full vector object in the console

Compare these with what you can find in the documentation.

We will come back to objects when we talk about classes. The takeaway here is that you can find out a lot about an object by printing it to the console.

console.log

Trying to call print in the global scope, ie. outside of the setup or draw functions:

print (`... and now for something completely different.`)

function setup () {
    createCanvas (400, 400)
}


function draw () {
  background (220)
}

... causes some very different behaviour:

an actual print

This is because print is repurposed inside p5. Under the hood, p5 is actually calling console.log (), which works both inside the special p5 functions, and oustide them:

console.log (`... and we're back.`)

function setup () {
    createCanvas (400, 400)
}


function draw () {
  background (220)
}

we have console back now

I generally use console.log (), as it is useful for debugging regardless of whether I am using p5.