I'm very new to javascript, node.js and express. My question is, how do I refactor the following code to make it one line inside the function?
exports.about = function(req, res){
var mytime = new Date();
res.render('about', {title: 'about page', time: mytime.toLocaleDateString() });
};
In other words, is there a way I can compress the var mytime = new Date(); and time: mytime.toLocalDateString() into one statement?
You don't. Readability over brevity. Let the machine do the minifying.
You could write mytime.toLocaleDateString() as (new Date()).toLocaleDateString(), but I wouldn't recommend it.
My prefered styling:
exports.about = function(req, res){
var mytime = new Date();
res.render('about', {
title: 'about page',
time: mytime.toLocaleDateString()
});
};
See Frits' answer: You can, but is there really any need? It's nice and readable the way you've done it.
But if you really, really want to, this is how:
exports.about = function(req, res){
res.render('about', {title: 'about page', time: new Date().toLocaleDateString() });
};
It looks a bit odd, but the new Date() part takes precedence, so you don't even needs parens around it (e.g., you don't need time: (new Date()).toLocaleDateString()). You could have them if you want, but they're not necessary.
ONE LINE
exports.about = function(req, res){ res.render('about', {title: 'about page', time: new Date().toLocaleDateString() }); };
This quite dumb though. There's nothing wrong with your original code.
Making this piece of code any shorter won't make it any better. I'd personally make it a little larger, like so:
exports.about = function (req, res) {
var mytime = new Date();
res.render('about', {
title: 'about page',
time: mytime.toLocaleDateString()
});
};
function since that's what JSLint wants.{ because that makes it more readable.You could do,
exports.about = function(req, res){
res.render('about', {title: 'about page', time: new Date().toLocaleDateString() });
};
But that's about it. I do agree with Frits van Campen.
My opinion is that it is better style to remove the mytime var because you are merely getting the current system time, and new Date() makes the intent perfectly clear.
exports.about = function (req, res) {
res.render('about', {
title: 'about page',
time: new Date().toLocaleDateString()
});
};