I am a bit confused with the default return value of lambdas in node.js. I found this link "Arrow Functions" :
Arrow functions can have either a "concise body" or the usual "block body".
In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
Which makes it pretty clear, but then I came upon this piece of Express code which I tested that returns the last statement by default without requiring to use "return":
const express = require('express');
const app = express();
app.use('/api/posts', (req, res, next) => {
const posts = [
{
id: 'sdfj234j654j',
title: 'First server-side post',
content: 'This is comming from the server'
},
{
id: '9054jk4ju59u90o',
title: 'Second server-side post',
content: 'This is comming from the server!'
}
];
// this is returned by default and does not require "return "
res.status(200).json({
message: 'Posts fetched succesfully!',
posts: posts
});
});
So which one is it do I need to use the return statement on lambdas when I use the block quotes to define them or not ? or is there an exception case which I am unaware of?
The arrow function in your example does not return anything. However it writes to the res
ponse by calling .json({ /*...*/})
, therefore it kind of "returns" the json to the client.
A simplified example:
setTimeout(() => {
console.log("test");
}, 1);
The above code outputs something to the console although nothing gets returned from the arrow function.