How do I reduce this code to one line?

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()
    });
};
  • I added a space after function since that's what JSLint wants.
  • I added a space before the { because that makes it more readable.
  • I placed all the object properties on different lines so I don't have to scroll horizontally all day (plus now I can add comments at the end of each property, yay!).
  • Finally I replaced the spaces-indentation with tabs because that makes everything align perfectly while only requiring one key-press to remove or go over them (if your caret is at the beginning of the line 4 spaces would require 4 keypresses to move to your code, while a single tab requires just one keypress).

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()
    });
};