How to checkered on JavaScript

Learn how to create a form validation with JavaScript and explore a simple example of code.

Checkered Pattern in JavaScript

A checkered pattern can be created in JavaScript with a very simple algorithm. To create a checkered pattern, we first need to create a two-dimensional array with a row and column of equal length. We then use a for loop to iterate through the array and assign alternating values of 0 and 1 to each cell. To display the pattern on the screen, we use a nested for loop to iterate through the array and display the corresponding value of each cell in the form of a table cell.


// Create a two-dimensional array
let arr = new Array(10);
for (let i = 0; i < 10; i++) {
  arr[i] = new Array(10);
}

// Assign alternating values of 0 and 1 to each cell
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    if ((i + j) % 2 == 0) {
      arr[i][j] = 0;
    } else {
      arr[i][j] = 1;
    }
  }
}

// Display the pattern on the screen
document.write("");
for (let i = 0; i < 10; i++) {
  document.write("");
  for (let j = 0; j < 10; j++) {
    if(arr[i][j] == 0) {
      document.write("");
    } else {
      document.write("");
    }
  }
  document.write("");
}
document.write("
");

The above code will create a checkered pattern of alternating white and black cells with a size of 10x10. The HTML table generated by this code can be seen below.

javascript formvalidation webdevelopment

Answers (0)