1

I'm experimenting with Array.map() and got this little snippet, which does perform as intended:

let cities = ["Buenos Aires", "Santa Fe", "Mar del Plata", "Mar de las Pampas"];

function urlify(string) {
  return string.split(" ").join("-").toLowerCase();
}

function functionalUrl(elements)  {
  return elements.map( element => urlify(element) );
}

console.log(functionalUrl(cities));

// ['buenos-aires', 'santa-fe', 'mar-del-plata', 'mar-de-las-pampas' ]

However, if I replace

return elements.map( (element) => urlify(element) );

with

return elements.map( (element) => { urlify(element); } );

(i.e., add parentheses and curly braces) it returns

[undefined, undefined, undefined, undefined]

I don't understand such behavior, as the curly braces/parentheses form is supposed to be "correct", and taking them away (I thought?) is just allowed in the specific case of a single-argument function... What am I missing here?

Thanks!

1
  • 1
    Beware: if you are using curly braces, you need to put return inside, otherwise, it will return void, which is undefined as you can see Commented Dec 26, 2019 at 18:44

1 Answer 1

4
elements.map( (element) => { urlify(element); } );

When you do the above code, you are creating the function body (assuming there are more lines of code to be included) and it expects the 'return' keyword, but if you are returning a single value (the result of one single computation), in your case

elements.map( (element) => urlify(element) );

then you don't have to specify the return keyword.

So the correct code for the second scenario using braces will be

elements.map( (element) => {return urlify(element)} );

The first one is a shorthand syntax not using the return keyword, also if you just have only one parameter you don't have to wrap the parameter inside the parenthesis. So the more concise way should be

elements.map( element => urlify(element) );
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.