Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does having [].map with curly brackets change the way it works?

Tags:

javascript

So, basically I have this:

Array.prototype.toString = function() {
    return ("[" + this.map(thing => thing = '"' + thing + '"').join(', ') + "]")
}

When I call it:

['foo', 'bar'].toString()

It returns

"["foo", "bar"]"

Now, THAT would work perfectly. This one (with curly brackets) doesn't seem to work like I wanted it to:

Array.prototype.toString = function() {
    return ("[" + this.map(thing => {thing = '"' + thing + '"'}).join(', ') + "]")
}

and it returns:

[, ]

So can someone tell me the difference? I don't know why [].map works like this.

like image 900
Chromata Avatar asked Nov 25 '25 14:11

Chromata


1 Answers

This has nothing to do with arrays or the map method. It is entirely about how arrow functions work.

When you give a single statement on the right hand side, then that statement is evaluated and returned inside the function.

foo => bar

is equivalent to:

function (foo) { return bar; }

When you put a block on the right hand side, that block simply because the function body.

foo => { bar }

is equivalent to:

function (foo) { bar; }

In this second version, you have no return statement, so the function returns undefined.

You need to make the return statement explicit if you use a block.

foo => { return bar; }
like image 199
Quentin Avatar answered Nov 28 '25 02:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!