How to avoid inserting NULL values to a table with JavaScript?

In order to get rid of null values inserted into a table, you need to check the condition while entering the value.

The condition to check NULL must be as follows −

while( !( yourVariableName1==null || yourVariableName2==null ||
   // yourStatement1

The above logic will never allow inserting the null values.

Now you can use for loop and insert value into the table without NULL. Following is the code −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<link rel="stylesheet" href="">
<h2>Demo Of Inserting the value into the table</h2>
<p>This is demo on the javascript array</p>
<p id="demo"></p>
   var index = 0;
   var firstNameArray = new Array();
   var lastNameArray = new Array();
   var firstName = "";
   var lastName = "";
   while (!(firstName == null || lastName == null)) {
      firstName = prompt("Please Enter your First Name=");
      lastName = prompt("Please Enter your Last Name=");
      firstNameArray[index] = firstName;
      lastNameArray[index] = lastName;
   document.writeln("<table border='1' width='50%'>");
   document.writeln("<caption>DEMO TABLE IN JAVASCRIPT</caption>");
   for (var startIndex in firstNameArray) {
      if (firstNameArray[startIndex] !== null &&
         lastNameArray[startIndex] !== null)
         document.writeln("<tr><td>" + firstNameArray[startIndex] +
         "</td><td>" + lastNameArray[startIndex] + "</td></tr>");

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −

Now entering the first name.

This will produce the following output −

After clicking the OK button, you will get the following output −

Now, entering the last name This will produce the following output −

After clicking the OK button, now click the button Cancel two times, you will get the final output.

The final output table is as follows −