Search code examples
javascriptvariable-types

JavaScript Integer Leading to NaN


I have JavaScript that basically looks like the following

function a() {
    b(1);
}

function b(myNumber) {
    c(myNumber);
}

function c(myNumber) {
    var calculation = 5 * (myNumber - 1);
    alert(calculation);
}

When I call the function a(), the alert box ends up saying "NaN". Why is this happening? I've tried using the parseInt() function in a number of places, but nothing seems to work.

EDIT

Full code (what's actually being done rather than a stripped down example):

function updateTablePagination(tableId, rowsPerPageSelectId) {
    updateTablePagination(tableId, rowsPerPageSelectId, 1);
}

function updateTablePagination(tableId, rowsPerPageSelectId, pageNumber) {
    var table = document.getElementById(tableId);
    var rowsPerPageSelect = document.getElementById(rowsPerPageSelectId);
    var rowsPerPage = rowsPerPageSelect.options[rowsPerPageSelect.selectedIndex].text;

    updateTable(table, rowsPerPage, pageNumber);
    //updateTablePageLinks();
}

function updateTable(table, rowsPerPage, pageNumber) {
    var tableRows = table.getElementsByTagName("tr");
    var totalNumberOfRows = tableRows.length;

    var startRow = rowsPerPage * (pageNumber - 1);      
     var endRow = Math.min(startRow + rowsPerPage, totalNumberOfRows - 1);

    alert("Start: " + startRow + "\nEnd: " + endRow);
}

A select box has an onchange calling updateTablePagination('myTableId', 'rowsPerPage'). The ids are both correct.

"Start" and "End" are both NaN.

Edit 2

Alternatively, if I just do alert(pageNumber), it is undefined.

Simplified

Even this says pageNumber is undefined:

function updateTablePagination(tableId, rowsPerPageSelectId) {
    updateTablePagination(tableId, rowsPerPageSelectId, 1);
}

function updateTablePagination(tableId, rowsPerPageSelectId, pageNumber) {
    alert(pageNumber);
}

Solution

  • You have two functions called updateTablePagination. Javascript does not support function overloading. Get rid of the first declaration, because it is getting overwritten with the second. You can use the || to define a default value for the parameter.

    function updateTablePagination(tableId, rowsPerPageSelectId, pageNumber) {
        pageNumber = pageNumber || 1; //Set a default value for pageNumber
        var table = document.getElementById(tableId);
        var rowsPerPageSelect = document.getElementById(rowsPerPageSelectId);
        var rowsPerPage = rowsPerPageSelect.options[rowsPerPageSelect.selectedIndex].text;
    
        updateTable(table, rowsPerPage, pageNumber);
        //updateTablePageLinks();
    }
    
    
    updateTablePagination(tableId, rowsPerPageSelectId) //Will call the function with pageNumber == 1