Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example:

3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

To achieve this, the user should provide the following inputs:

(1) The number they want to create the table for (e.g., 3)

(2) Specify the starting point (e.g., 1)

(3) Specify the ending point (e.g., 4)

Below is the code snippet illustrating my current attempt:

    function validateNumber(number){
        while (isNaN(number) == true){
         number = parseInt(prompt("Please enter a valid number","5"));
         }
         }
    
    
    function mathTable (num, start, end){
        for (var i=start; i<=end; i++){
        var result = num*i;
        document.write(num + " x " + i + " = " + result + "</br>");
         }
        }
    
    
    var inputNum = parseInt(prompt("Enter the number you want the table for", "40"));
    inputNum = validateNumber(inputNum);
    
    
    var startPoint = parseInt(prompt("Enter the start point of the table", "1")); 
    startPoint = validateNumber(startPoint);
    
    var endPoint = parseInt(prompt("Enter the end point of the table", "10"));  
    endPoint = validateNumber(endPoint);
    
    
    mathTable(inputNum, startPoint, endPoint);

Answer №1

CheckIfNumber returns null (default output for functions lacking a return statement), which is then stored in the variable checkNum each time (checkNum = CheckIfNumber(...)). Consequently, the value of checkNum is null.

Upon completing the loop over the NaNs, ensure that you return the variable and assign it to the correct one:

function CheckIfNumber(number)
{
    while (isNaN(number)) {
            number = parseInt(prompt("Please enter a valid number","5"));
    }
    return number;
}

function myGrid (num, beginning, end)
{
    for (var j = beginning; j <= end; j++) {
        var z = num * j;
        document.write(num + " x " + j + " = " + z + "</br>");
    }
}

var checkNum = parseInt(prompt("Enter the number you want to generate a table for", "40"));
checkNum = CheckIfNumber(checkNum);

var startLocation = parseInt(prompt("Enter the starting point of the sequence", "1")); 
startLocation = CheckIfNumber(startLocation);

var finishLocation = parseInt(prompt("Enter the ending point of the sequence", "10"));  
finishLocation = CheckIfNumber(finishLocation);

myGrid(checkNum, startLocation, finishLocation);

Answer №2

You have committed the following errors:

inconsistent function return values, misaligned startpoint variable assignment, incorrect endpoint variable assignment

function checkIfNumber(number){
    while (isNaN(number) == true){
            number = parseInt(prompt("Please enter a valid number","5"));
        }
        return number;
     }


function createTable (num, firstVal, secondVal){
    for (var i=firstVal; i<=secondVal; i++){
        var result = num*i;
        document.write(num + " x " + i + " = " + result + "</br>");
     }
    }


var inputNum = parseInt(prompt("Enter the number you want to generate a table for", "40"));
inputNum = checkIfNumber(inputNum);


var startPoint = parseInt(prompt("Enter the starting point of the table", "1")); 
startPoint = checkIfNumber(startPoint);

var endPoint = parseInt(prompt("Enter the ending point of the table", "10"));  
endPoint = checkIfNumber(endPoint);


createTable(inputNum, startPoint, endPoint);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

Retrieve the text label from the parent option group

Below is the HTML code snippet: <select id="categoryg"> <optgroup label="Main" value="binding"> <optgroup label="Sub" value="binding"> <option value="46&quo ...

Learning to access a base64 encoded PDF file using JavaScript

var ajaxSettings = { url: urls.orders.list+"/"+singlePacket.requests[0].order_id+"/labels", //retrieve labels with ShipperAssigned status type: "GET", contentType: "application/json", headers: { "Authorizatio ...

The OutlinedInput component from Material-UI seems to be struggling to display the startAdornment

Below is the code snippet. The start adornment is not displaying in the textfield, and there is no text appearing on the label. <InputLabel>Mobile Number</InputLabel> <OutlinedInput variant="outlined" ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

Trigger a page refresh using a popup

Exploring the world of React for the first time has been quite a journey. I've encountered a hurdle in trying to force my page to render through a popup window. The setup involves a function component with a popup window that allows text changes on t ...

"Sorry, but there seems to be an issue with

My shop: { customers: [ { id: 12345, name: Customer A }, { id: 54321, name: Customer B } ] } I am attempting to modify the name attribute for Customer A. I am utilizi ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

The duplication of the Javascript code is creating a conflict within the slider functionality

Attempting to create both an image slider and text slider on the same page using the same JavaScript is proving to be a challenge. Despite researching and trying to implement a no-conflict solution, the sliders still do not function properly together. Wh ...

Error in Function Due to Undefined jQuery DataTable Parameters

In the jQuery datatable column, the below JavaScript code will display either a green checkmark button or a red X button: { data: "HasPayment", render: function (data, type, row, meta) { if (data) { return '<bu ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

How to change class names dynamically in Vue.js?

I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...

Leverage JSON data from an API within JavaScript, sourced and accessed through PHP

I'm seeking advice on using JSON data (loaded in PHP) with JavaScript. I am currently retrieving the JSON from an API, but someone suggested that using curl would be more efficient? I've attempted to research curl, but haven't found exactly ...

Establishing session management for tasks in Node.js

I'm currently developing a web application using Node JS and encountering an issue with the session store in req. For my sessions to work, I have set up my app.js like this: // Enable sessions app.use(session({ secret: '***********', ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Ways to set the initial value of an input[range] in Angular2 when the value exceeds 100

After encountering a similar issue with AngularJS, I posted a question on StackOverflow titled How to initialize the value of an input[range] using AngularJS when value is over 100. As I dive into learning Angular2, I am curious if it handles initializatio ...

Transferring information from nodejs/express to frontend JavaScript

I am faced with a challenge regarding accessing the 'data' sent from my backend server in my frontend js. Can anyone guide me on how to achieve this? Express ... app.get("/", (req, res) => { res.render("home", {data} ); }); ... home.ejs ...

Using React Bootstrap, you can ensure that only a single collapse opens at a time when rendering it with a map function. This allows you to display

When a user clicks on the "View Tasks" button, I want to display the relevant tasks specific to that user. However, currently all React Bootstrap Collapse Components open up and show tasks for every user instead of just one. This issue arises because the o ...