I cannot declare and create an object in one line

I’ve come across two ways of defining classes in p5.js.

The first: https://editor.p5js.org/femkeblanco/sketches/Vycw0YkNr
The second: https://editor.p5js.org/femkeblanco/sketches/YXi8pCrRQ

I presume the second way, which I came across in the book “Getting Started with p5.js”, is legacy. Is that correct?

My main question is the following:

I cannot declare and create an object in one line at the top using the first way: https://editor.p5js.org/femkeblanco/sketches/f7xH0mqRX

I have to create the object in setup(): https://editor.p5js.org/femkeblanco/sketches/Vycw0YkNr

But I can declare and create an object in one line at the top using the second way: https://editor.p5js.org/femkeblanco/sketches/YXi8pCrRQ

Why, why and why?

Your help is appreciated and thanks in advance.

2 Likes

JS got 6 keywords that can be used to declare variables:

  1. varvar - JavaScript | MDN
  2. functionfunction - JavaScript | MDN
  3. letlet - JavaScript | MDN
  4. constconst - JavaScript | MDN
  5. classclass - JavaScript | MDN
  6. importimport - JavaScript | MDN

Outta those 6 declaration keywords, the primeval 1s var & function, which existed since the very beginning of JS, got an exotic behavior called hoisting:

Variables declared via var or function already exist from the top, even when they’re declared much further down!

For a more detailed explanation about hoisting, go to the article’s link below:

Given keyword class doesn’t hoist like function does, as a workaround, move the whole class to the top, before it’s used by anything else.

4 Likes