-2

I am having issues trying to run a simple function with an array, it runs undefined, but when I console log it I get th right result?

Please can anyone help?

var test = (function (newThing){

  newThing = [1,2,3,4,5,6];

  var  myarray = newThing.map(n=>n*n)
    .reduce((a,b)=> {return a+b});

  return myarray;
})();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
sat
  • 1,009
  • 3
  • 19
  • 41
  • 2
    The console always try to log the return value of any expression. `var x = 1` yields no return value, so it shows `undefined`. Remove `var test =` and you will see the return value in the console. – BrunoLM Jan 08 '17 at 14:00
  • I rolled back the edit because running the code in a snippet doesn't replicate the behavior the OP is describing. (My answer is a CW because I'm **sure** there's a duplicate, so I didn't reopen.) – T.J. Crowder Jan 08 '17 at 14:00
  • 2
    Duplicate, probably: [Why does JavaScript variable declaration at console results in “undefined” being printed?](https://stackoverflow.com/questions/22844840/why-does-javascript-variable-declaration-at-console-results-in-undefined-being) – apsillers Jan 08 '17 at 14:01
  • @apsillers: Thank you! I knew there was one. – T.J. Crowder Jan 08 '17 at 14:02

1 Answers1

3

It's because when you paste that code into the console, the console shows the result of the var declaration, which is undefined. The code is fine, and test gets set correctly, it's just the effect of running code starting with var in the console.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875