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);

2
  • Please create an minimal reproducible example. What you've shown is conceptual, let's see an actual working example. Commented Mar 29, 2019 at 15:24
  • 3
    x.map(v => x+1): x is the array, v the current element, hence x+1 should be v+1 Commented Mar 29, 2019 at 15:24

3 Answers 3

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])
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.