javascriptarraysdom

In Javascript, why is [somevar] considered an array?


In Javascript, the following declaration is from a text input:

numberInput = document.getElementById('number-input');

In HTML, "number-input" is this:

<input type="number" id="number-input" />

The numberInput variable is passed to a function like this:

function processInputs(list) 
  let total = 0;
  // add the items in list to a total
  for (const item of list) {
    total += item;
  }

Why does the statement processInputs([numberInput]) treat numberInput as an Array/NodeLIst ?


Solution

  • The code you are presenting is wrong...

    at a minima it should be:

    const numberInput = document.getElementById('number-input');
    // "const" is missing in your code
    
    
    function processInputs(list)
      {                           // "{" is missing in your code
      let total = 0;
      // add the items in list to a total
      for (const item of list)
        { 
        total += item.valueAsNumber;  // ".valueAsNumber" is missing in your code
        }  
      console.log( total );    // added for showing result
      }
    
    processInputs( [numberInput] );
    
    /* same as :
    
    let fct_Argument = [numberInput];
    console.log( typeof fct_Argument );  // ---> Array
    
    processInputs( fct_Argument );
    
    */
    <input type="number" id="number-input" value="50" />