Need help understanding how invalidInputMatch function works for calorie counter project

I have a different question about this step, step 61 of Learn Form Validation by Building a Calorie Counter.

My question is about [quote]
alert(Invalid Input: ${invalidInputMatch[0]})
[/quote]. I don’t understand what zero part of ${invalidInputMatch[0]}. Does this mean invalid input is housed in

invalidInputMatch[0]  

If not, why does invalid input point to this value invalidInputMatch[0]?
Where does this value come from? I am very confused about this line alert(`Invalid Input: ${invalidInputMatch[0]}`);. I do not understand this line, and I have gone through this more than once.

I created a new topic for you.

Here is the starting code

function getCaloriesFromInputs(list) {
  let calories = 0;

  for (let i = 0; i < list.length; i++) {
    const currVal = cleanInputString(list[i].value);
    const invalidInputMatch = isInvalidInput(currVal);

    if (invalidInputMatch) {

    }
  }
}

this function call here represents the cleaned user input

cleanInputString(list[i].value)

we assign that to the currVal variable.

then this function call here checks for an invalid input

isInvalidInput(currVal)

here is the isInvalidInput function it is referencing

function isInvalidInput(str) {
  const regex = /\d+e\d+/i;
  return str.match(regex);
}

the return value will be an array of matches if there are any, or it will return null

For this line here, we are checking if invalidInputMatch is truthy. In this context, if there are any matches for invalid inputs.

if (invalidInputMatch)

If we do have invalid matches, then that means we are dealing with an array.

So invalidInputMatch[0] would access the first element of that matches array.

hope that helps

1 Like

Thank you for your response. I am not trying to be a hard a**. I don’t understand why it’s always reading ‘’‘invalidInputMatch[0]’‘’. It is not clear what’s
in ‘’‘invalidInputMatch[0]’‘’ even with a few more steps down the road. What’s in ‘’‘invalidInputMatch[0]’‘’?

When the user provides an invalid input, an alert will show with that value they tried to submit.

You can test this out by doing the following

  1. go to final step of the project
    https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/learn-form-validation-by-building-a-calorie-counter/step-94

  2. click on the add entry button

  3. for Entry 1 Calories, add 2e10
    Screenshot 2024-01-30 at 10.31.29 PM

  4. add a budget
    Screenshot 2024-01-30 at 10.32.08 PM

  5. click on calculate calories
    Screenshot 2024-01-30 at 10.32.33 PM

You should see this alert show up displaying the input you provided. For the context of the calorie counter, this input of 2e10 would be considered invalid because we only want to deal with regular number values. Not scientific number values.

hope that helps

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.