skip to Main Content

I want to test a simple program with node:

let myArray = [1, 2, 3, 4, 5];
function doubleInput(arrayItem) {
  return arrayItem * 2;
}

But for some reason nothing outputs when i do node.js in the terminal. Am i missing something? I do have node installed (v20.3.0).

My output should be:
2, 4, 6, 8, 10

But sadly, nothing shows up

I simply have just a test.js file that has an array with values and then a function that multiplies by two and returns that result. I tried adding a .npmignore file, a package lock and package.json adding in i still have the same results. Also in terminal i do

node test.js

3

Answers


  1. Your code outputs nothing, because you’re not calling your function, and you’re not printing anything.

    I would also suggest using map in your case. You can use it like this:

    let myArray = [1, 2, 3, 4, 5];
    
    result = myArray.map(x => x * 2)
    
    console.log(result);

    Outputs

    [ 2, 4, 6, 8, 10 ]

    Login or Signup to reply.
  2. You actually didn’t call your function doubleInput, that’s why you didn’t get any output,
    Even though you invoke it, you gonna get NaN since return arrayItem * 2; is like [1, 2, 3, 4, 5] * 2 which always gives NaN;

    The right way is looping over each value, Doubling it and storing it in an array, and finally returning that variable.

    let myArray = [1, 2, 3, 4, 5];
    function doubleInput(arrayItems) {
      let returnedArrayOfItems = [];
      for(let i=0; i<=arrayItems.length-1; i++){
        let arrayItem = arrayItems[i];
        returnedArrayOfItems.push(arrayItem*2);
      }
      return returnedArrayOfItems;
    }
    console.log(doubleInput(myArray))
    Login or Signup to reply.
  3. You can use map method and join

    let myArray = [1, 2, 3, 4, 5];
    
    function doubleInput(array) {
        return array.map(x => 2 * x);
    };
    
    let res = doubleInput(myArray);
    
    console.log(res.join(', '));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search