Search code examples
javascriptnode.jsmagic-numbers

Avoid magic number when referencing an array


I can't find a straightforward answer to this. How do I refer to parts of an element without using magic numbers?

In this case I am trying to place values of several cells from a row from an HTML table into variables:

const age = personRow.cells[1].innerText;
const sex = personRow.cells[2].innerText;

Solution

  • I've had this issue before when using Google Sheets API to manipulate spreadsheets. You could just do:

    const AGE_COL = 1;
    const SEX_COL = 2;
    
    const age = personRow.cells[AGE_COL].innerText;
    const sex = personRow.cells[SEX_COL].innerText;
    

    For simple code this works and is fairly self-documenting. However, you may need to handle several different types of table "structure". My solution to this is:

    const FIELDS = {
        PERSON: {
            AGE: 1,
            SEX: 2
        }
    }
    
    const age = personRow.cells[FIELDS.PERSON.AGE].innerText;
    const sex = personRow.cells[FIELDS.PERSON.SEX].innerText;
    

    I find this to be even more readable and easier to extend.