Displaying the date in MM/DD/YY format I spent about an hour and a half attempting to complete a problem from W3Resource. Here is what I came up with, which works. How can I shorten it?

function dateGet(){
var newDate = new Date();
var newMonth = newDate.getMonth() + 1;
var newDay = newDate.getDate();
var newYear = newDate.getFullYear();
var twoYear = (""+newYear).split("");
var combinedYear = twoYear[2] + twoYear[3];
var fullDate = 0;

if (newMonth &lt; 10){
    fullDate += 0 + newMonth + '/';
} else {
    fullDate += newMonth + '/';
}

if (newDay &lt; 10){
    fullDate += 0 + newDay + '/';
} else {
    fullDate += newDay + '/';
}

if (combinedYear &lt; 10){
    fullDate += 0 + combinedYear;
} else {
    fullDate += combinedYear;
}

console.log(fullDate);

}
Whenever you find yourself writing code that feels the same, consider whether you can create a function to do it. For example consider using a function for padding to two digits.



Instead of turning newYear into a string so you can split it on digits, consider using the remainder operator (%). That is, var newYear = newDate.getFullYear() % 100; 

Although (actually, because) javascript lets you play fast and loose with whether a variable is a string or a number or something else, it's worth avoiding switching between them where possible. It also has the slight advantage that it always gets the last two digits, even if the year had 3 or 5 digits in it. (Of course that won't be relevant for a very long time if it only prints the current date, but you shouldn't bank on that.)



I would be inclined to make this code slightly more general by allowing it to return rather than print out the formatted string, and allowing it to take a Date as a parameter rather than only using the current date. If you do want to print it, you can always do that with the output. 

Of course that might actually be marginally longer, but I think that's worth it. Unless you're in a smallest number of characters competition, it is better to have readable, flexible code than short code if they conflict. Length is only a problem when there's too much there to keep in your head how it fits together.



Sticking strings together one bit at a time with + is an expensive thing to do. It's worth getting into the habit of using something like join As shown in jstudenski's code.