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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With