Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
ReferenceError: Cannot access 'Block' before initialization

I'm writing some js code for doing tetris for a school project, and I got stuck with a class I wrote. This is the code:

let canvas = document.getElementById("mainWindow");
let cnv = canvas.getContext("2d");

class Block { //da fixare
  constructor(shape, color, rotate) {
    this.shape = shape;
    this.color = color;
    this.rotate = rotate;
  }
}

function randomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomColor(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  let color = Math.floor(Math.random() * (max - min + 1)) + min;
  switch (color) {
    case 1:
      return "red";
    case 2:
      return "yellow";
    case 3:
      return "blue";
    case 4:
      return "green"
    case 5:
      return "light-blue";
    case 6:
      return "indigo";
    case 7:
      return "orange";
  }
}

function newBlock() {
  let blockObj = new Block(randomInt(1, 1), randomColor(1, 1), randomInt(1, 1));
  console.log("figura generata: ");
  if (blockObj.shape == 1) {
    console.log("quadrato ");
  }
  if (blockObj.color == "red") {
    console.log("rosso ");
  }
  if (blockObj.rotate == 1) {
    console.log("orizzontale");
  }
}

newBlock();
<canvas id="mainWindow"></canvas>
When I try to call the newBlock() function, the console gives me this error:

Uncaught ReferenceError: Cannot access 'Block' before initialization
    at newBlock (tetris.js:43:5)
    at <anonymous>:1:1

I also searched on the internet for the solution but everyone says you have to declare the class before the function, as in my code. How can I fix this?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!