1

Why is this not working?

var numbers = [1,2,3,4,5,6,7,8];
var stringifiedNumbers = numbers.map(function(x) { 
   JSON.stringify(x);
})
console.log(stringifiedNumbers);

Why is my output:

Array [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ]

1
  • 2
    Also seems total overkill to use JSON.stringify for a simple numeric. Just use return x.toString() Commented May 11, 2017 at 12:21

1 Answer 1

5

You're not returning the stringified content so the function transforms the array into undefineds. Array#map transforms each array element based on the return value of the passed callback and since yours returns nothing it transforms them to undefined:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var stringifiedNumbers = numbers.map(function(x) {
  return JSON.stringify(x);
})
console.log(stringifiedNumbers);

You could shorten this with arrow functions:

var stringifiedNumbers = numbers.map(x => JSON.stringify(x));

Because you are only using one return statement in the example above, you can implicitly return the expression with an arrow function. You could even just shorten it to:

numbers.map(JSON.stringify);

As it implicitly passes the argument and gets rid of the variable.

Sign up to request clarification or add additional context in comments.

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.