Getting the date on YYYYMMDD format I'm looking for the best way to return a date on a YYYYMMDD format, such as 20180106.

Here is how I do it:

var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) &amp;&amp; (d = '0' + d);
(m.length == 1) &amp;&amp; (m = '0' + m);
var yyyymmdd = y + m + d;
alert(yyyymmdd);


Is it correct enough or can I achieve the same in a better way?
The code looks good and works well. Since it provides a useful bit of work, you should convert it into a function. Then you can copy that function to another program if you need so.

function yyyymmdd() {
    var x = new Date();
    var y = x.getFullYear().toString();
    var m = (x.getMonth() + 1).toString();
    var d = x.getDate().toString();
    (d.length == 1) &amp;&amp; (d = '0' + d);
    (m.length == 1) &amp;&amp; (m = '0' + m);
    var yyyymmdd = y + m + d;
    return yyyymmdd;
}


To make this code a little easier to read, you should rename x to now.

You could also omit the calls to toString(), which makes the code a little shorter. Plus, you should introduce the variables mm and dd, so that you don't reassign to the d and m variables. This is a generally useful pattern, because when stepping through the code you can always look at the variable definition to see how it was computed. This is not possible for variables that change their value during execution.

The modified code looks like this:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    var mm = m &lt; 10 ? '0' + m : m;
    var dd = d &lt; 10 ? '0' + d : d;
    return '' + y + mm + dd;
}


Or, you could inline the last few lines:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    return '' + y + (m &lt; 10 ? '0' : '') + m + (d &lt; 10 ? '0' : '') + d;
}


That last variant is harder to read though, therefore I prefer the previous one.

Another possibility is to define a helper function that produces a two-digit string:

function yyyymmdd() {
    function twoDigit(n) { return (n &lt; 10 ? '0' : '') + n; }

    var now = new Date();
    return '' + now.getFullYear() + twoDigit(now.getMonth() + 1) + twoDigit(now.getDate());
}