Learn Form Validation By Building a Calorie Counter

Hello everyone,
Question regarding the getCaloriesFromInputs() function in the Calorie Counter project:

function getCaloriesFromInputs(list) {
  let calories = 0;
  for (const item of list) {
    // console.log(typeof item); returns object
    // console.log(type of item.value) returns string
    const currVal = cleanInputString(item.value);
    const invalidInputMatch = isInvalidInput(currVal);

    if (invalidInputMatch) {
      alert(`Invalid Input: ${invalidInputMatch[0]}`);
      isError = true;
      return null;
    }
    calories += Number(currVal);
  }
  return calories;
}

In this function we are accessing the nodeList that was created from our querySelectorAll method in the calculateCalories() function. I was experimenting with typeof and noticed that:

// console.log(typeof item); returns object
// console.log(type of item.value) returns string

When one uses the .value method on a node object from a nodeList, does it always return the value as a string even if the input is a number?

Thank you.

Hello, its going to come back as a string no matter what because thats all it can do. a value in HTML is always wrapped in quotation marks. To convert strings to numbers use parseInt() or parseFloat()

1 Like

I understand now. I was googling the wrong thing. A value retrieved from a HTML input field will always be a string. Thanks for the help!.

1 Like