0

Playing around with some code I found and the results do not make sense to me.

I do not understand why the REPL thinks the array is one long string value.. I have done nothing to indicate this is a string and I am wondering why the console is giving me the following result.

F = (...x) => x.map(v => x+1)

//ACTUAL
F([1,2,3]) //["1,2,31"]

//EXPECTED
F([1,2,3]) //[2,3,4]

var F =(...x) => x.map(v => x+1)  
var result = F([1,2,3]);
console.log(result);
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0TTT0
  • 1,288
  • 1
  • 13
  • 23

3 Answers3

3

You are passing an array as an argument since you are using Rest parameter for function parameter the value of x would become [[1,2,3]]. Now when you are using map, on first iteration v would be [1,2,3] and [1,2,3] + 1 would result in string concatenation since [1,2,3] is not a number and while [1,2,3] coverts to a string it results a string with comma separated value.

So either pass arguments as multiple or use a simple parameter.

Like :

function F(x){ return  x.map(v => x+1) }

or call function like:

F(1, 2, 3)
// or
F(...[1, 2, 3])
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

You are making two mistakes.

  • You are using Rest Parameters but you are passing an array.
  • You are adding to x which is array and will be converted to string by usage of +. You return v+1

const F=(x) => x.map(v => v+1)
console.log(F([1,2,3]))

If you want to use Rest Parameters then simply pass 1,2,3 as separate arguments.

const F=(...x) => x.map(v => v+1)
console.log(F(1,2,3))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You're looking for F = x => x.map(v => v+1), thus...

F([1,2,3]) == [2, 3, 4] # evaluates to true

There's no need for the spread syntax. The function F should just accept an array so that it returns the result of [1,2,3].map(v => v+1). You had x.map(v => x+1) which is not using the v parameter of the function being passed into the .map() function.

Steven
  • 3,526
  • 3
  • 18
  • 28