MZ MV/MZ - ES6 and you: cool stuff you might not know you can do.

So one thing that's been made apparent to me over the last few weeks is that there are a fair few coders in the community who aren't yet aware of some of the coolest stuff ES6 gave us, so this is just a topic to bring your attention to those things and hopefully make your coding lives a bit easier.

Let and Const
If you've come from MV, or are still there, you're going to be intimately familiar with var. There's barely a plugin from the earlier days that doesn't have it somewhere, and obviously it serves to create variables in code. If you need a value with a specific name that you'll use later, you declare it with var. So what are let and const?
Well, they're basically var with more structure: let defines variables that can change within the block you declared them, and const defines constant variables where the value will never change. If it changes, let. If it doesn't, const. Simple.
For example, I can do:

JavaScript:
let x = 5;
x = 10;
console.log(x);
// output: 10

But I can't do
JavaScript:
const x = 5;
x = 10;
if I try to run this, I'll get an error because I tried to assign a value to a constant. This is handy to keep your mutable values and immutable ones safe from accidental operations; with var, there's nothing stopping you from changing a value even if it's meant to be a constant. The reasons behind no longer using var as many, and rather than try to cover them all in one topic, I'll link to a great article that explains the issues with it and why we should stop using var entirely wherever possible:


Arrow Functions
Arrow functions are basically syntactic sugar for anonymous/unnamed functions, cutting out a fair amount of bloat we no longer need to include. For example, in ES5, when passing a callback function to forEach:

JavaScript:
[1, 2, 3, 4, 5].forEach(function(value) { console.log(value) });
// output
1
2
3
4
5


What we can do now is take out the "function" keyword and the brackets around the parameter name, remove the "return" keyword if one was needed, and use an arrow (=>) to replace the block brackets. So it becomes:

JavaScript:
[1, 2, 3, 4, 5].forEach(value => console.log(value));
// output as above
Much neater! But Trihan, what if we have multiple parameters? I hear none of you ask. Well then you just put the brackets back:
JavaScript:
[1, 2, 3, 4, 5].reduce((accumulator, value) => accumulator + value, 0);
// output 15

Note that the return keyword isn't needed for this, where it would have been in ES5.
As pointed out by @TheoAllen, you can store arrow functions in variables like you can with others:
JavaScript:
const fn = () => console.log("stuff");

Multi-line Strings
Strings can now be declared with visible newlines by enclosing them in backticks instead of quotes. So instead of

JavaScript:
const string = "This\nspans\nmultiple\nlines";

you can do

JavaScript:
const string = `This
spans
multiple
lines`;

Parameter Defaults
In ES5, defining default values for a parameter had to be done in-block using a logical OR. For example:

JavaScript:
var calculateArea = function(width, height) {
  width = width || 100;
  height = height || 80;
  return width * height;
}

But now, in ES6, we can include the defaults in the parameter definition:

JavaScript:
var calculateArea = function(width = 100, height = 80) {
  return width * height;
}

And you can even combine that with arrow functions to make it even more streamlined:

JavaScript:
const calculateArea = ((width = 100, height = 80) => width * height);
calculateArea();
// output 4000


Template Literals
This is a fun one. So in ES5, when placing variables into strings, you had to terminate the string, concatenate the variable, then reopen the string to continue. Like so:

JavaScript:
var variable = 5;
console.log("The variable's value is " + variable + ".");

But now, thanks to the ever-trusty backtick, that's a thing of the past because we can use template literals to put the variable right into the string without having to interrupt it!

JavaScript:
const variable = 5;
console.log(`The variable's value is ${variable}.`);
Spread Operator
You can actually see this one in the base MZ code for constructors. The spread operator takes the iterable object that follows it and expands it into individual arguments; this can be used in any place where zero or more arguments or elements are expected, so you can use it in function calls or array assignment.
If you've ever looked at the MV base code, you'll have seen a lot of things like this:
JavaScript:
function ClassName() {
  this.initialize.apply(this, arguments);
}
And if you look at MZ, you'll more than likely see this instead:
JavaScript:
function ClassName() {
  this.initialize(...arguments);
}
These do the same thing, it's just that in ES5 we didn't have any way to extract an array into distinct values when passed to a function. To give a concrete example:
JavaScript:
const args = ["Trihan", "JavaScript", "developer"];
function myFunc(name, language, profession) {
  console.log(`My name is ${name} and I'm a ${language} ${profession}!`);
}
myFunc(...args);
Output: "My name is Trihan and I'm a JavaScript developer!"

Among its other uses, you can use this for array assignment; in fact, this is the example that prompted me to write this topic in the first place:

JavaScript:
let arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10];
arr1 = [...arr1, ...arr2];
console.log(arr1);
// output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Destructuring Assignment
This feature makes it easier to extract values from arrays and properties from objects into distinct variables:

Array destructuring:
JavaScript:
const animals = ["dog", "cat"];
const [ani1, ani2] = animals;
console.log(ani1, ani2);
// output "dog cat"

Object destructuring:
JavaScript:
const dog = { name: "Boss", breed: "Malamute" };
const { name, breed } = dog;
console.log(name, breed);
// output "Boss Malamute"

Enhanced Object Literals
In ES5, when creating an object's properties and assigning them via variable, you had to declare the property:
JavaScript:
const name = "Trihan";
const occupation = "Developer";
const age = 37;
const person = { name: name, occupation: occupation, age: age };
Well now you don't have to do that!
JavaScript:
const name = "Trihan";
const occupation = "Developer";
const age = 37;
const person = { name, occupation, age };
As long as the property name is going to be the same as the variable identifier, there's no need to explicitly declare it any more.

Promises
Promises are JavaScript's answer to asynchronous processing. They're a bit complex to get to grips with if you're not used to async functions but Kino has a great explanation of them here:

Classes
ES6 has classes now! That's great! But there are some things to be aware of. First of all, let's look at how we used to have to create a "class" vs how we do it in ES6:

ES5:
JavaScript:
function Window_CustomFunc() {
  this.initialize.apply(this, arguments);
}

Window_CustomFunc.prototype = Object.create(Window_Base.prototype);
Window_CustomFunc.prototype.constructor = Window_CustomFunc;

Window_CustomFunc.prototype.initialize = function(rect) {
  Window_Base.prototype.initialize.call(this, rect);
  // other window-specific stuff
};

Window_CustomFunc.prototype.someFunction = function() {
  // more stuff
};

ES6:
JavaScript:
class Window_CustomFunc extends Window_Base {
  constructor(rect) {
    super(rect);
    // other window-specific stuff
  }

  someFunction() {
    // more stuff
  }
}

As you can see, there's a lot less involved. But it's important to remember that JavaScript still does not have classes. This is just syntactic sugar for the same code we used to use before, and under the hood JavaScript classes don't have the same sort of features and real inheritance that other languages do. It's still a lot cleaner and easier to write, though.


Modules
Not something I really use myself, but including it here for the sake of completion. Modules are represented by separate .js files, and we can use the export/import statements to either make a module object available externally, or import one from another module:

module.js
JavaScript:
export const myConst = 5;
export function myFunc() { // stuff }

some_other_file.js
JavaScript:
import { myConst, myFunc } from 'module'
console.log(myConst);
output: 5

And that's mostly it for the new stuff in ES6! Hopefully there was something here that you either didn't know about or didn't fully understand yet. Let me know in the comments if I've missed anything out or you have further insight on lesser-known JS features!
Also, you can store the arrow function in a variable.
JavaScript:
let arrfn = () => { console.log("") }

Also, you forgot about the spread operator.
Also, you can store the arrow function in a variable.
JavaScript:
let arrfn = () => { console.log("") }

Also, you forgot about the spread operator.
I confused myself and thought spread operator was ES5 since the base MZ code uses it but doesn't use class notation. I'll add it in the morning.
I could probably look it up, but I think it would be good to have the info here 🙂

Your thread header says MV/MZ - is there a version of MV where it got updated to ES6, or would you need to use one of the other tutorials to manually update NWJS?

For example, I remember being pretty psyched when I found out about the optional chaining operator, but then it threw errors when I tried to use it in MV code.

Regarding the article, for me and my background, the functionality of const is actually confusingly counter-intuitive. In its example:
Code:
function printMatrix (matrix) {
  for (let i = 0; i < matrix.length; i++) {
    const line = matrix[i];
    for (let i = 0; i < line.length; i++) {
      const element = line[i];
      console.log(element);
    }
  }
}

To me, that shouldn't work 🤣 The variables being declared as constant actually aren't, they're clearly changing with each iteration if the code is producing the desired/expected output.

I understand that it does work, and the article is not clear to me whether it works because the const is being set as a reference to matrix[i] and therefore reflects any modification to that, or if it's getting redefined in each iteration of the loop...but it messes with my preconceptions of how const ought to function.

I guess there's not a real conversation point to all of that, I'm not trying to say people shouldn't use const...just complaining, I suppose 😉
the article is not clear to me whether it works because the const is being set as a reference to matrix[i] and therefore reflects any modification to that, or if it's getting redefined in each iteration of the loop...
I'm not sure if you already know the reason or not, but for a sake of answering this for everyone else, it is the latter. The code block is its own scope. It is basically undefined outside of that. So, every iteration is just its own code block. A new constant is declared each time in a different block.
Your thread header says MV/MZ - is there a version of MV where it got updated to ES6, or would you need to use one of the other tutorials to manually update NWJS?

For example, I remember being pretty psyched when I found out about the optional chaining operator, but then it threw errors when I tried to use it in MV code.
AFAIK, you can use ES6 in the latest version of MV. However, optional chaining came some time after ES6 (I think like ES11 or something).
To throw my two cents here,

First of all this is great thread!

There are some attentions:

Arrow function is more than syntax sugar. It uses lexical scope and you can't use bind to it for example.

And what it comes to let and const they are faster to read than var. JS interpreter won't have to check if they have been 're-declared'. And const is the fastest to read cause there's no 'value changed' check either. These uses less CPU time and thus it uses less electricity let's save the world!

Var should be used only when you do not know if it has been already declared or it can be re-declared later. Var is also the most 'unsafe' to use for the said reasons.
Some great additions there, and good call on the omission of optional chaining and by extension null-assignment! I'll add those when I edit in spread operator.
Some great additions there, and good call on the omission of optional chaining and by extension null-assignment! I'll add those when I edit in spread operator.
But just to reiterate, optional chaining and nullish assignment aren't part of ES6 and are not available to MV users who haven't manually updated NW.js to a higher version, so you might need to change the title of the thread and/or add in some type of disclaimer if you decide to cover those.
Neat little tricks, hope you add more along the way 😉.
But just to reiterate, optional chaining and nullish assignment aren't part of ES6 and are not available to MV users who haven't manually updated NW.js to a higher version, so you might need to change the title of the thread and/or add in some type of disclaimer if you decide to cover those.
Gah, you're right. This is what I get for commenting in the early hours of the morning and right after I wake up

OP is updated with spread operator. @ATT_Turan it's already been answered, but yeah, the latest version of MV supports these features.
This is a really well done tutorial, thank you!
JavaScript:
const args = ["Trihan", "JavaScript", "developer"];
function myFunc(name, language, profession) {
console.log(`My name is ${name} and I'm a ${language} ${developer}!`);
}
myFunc(...args);

Output: "My name is Trihan and I'm a JavaScript developer!"
re-reading this code, gives an error of "devoloper of undefined"!
as developer is never defined, but profession that I now see it 😀

but still usefull though 🙂
re-reading this code, gives an error of "devoloper of undefined"!
as developer is never defined, but profession that I now see it 😀

but still usefull though 🙂
Oh whoops! Thanks for the spot, I'll edit.

Original thread: https://forums.rpgmakerweb.com/threads/mv-mz-es6-and-you-cool-stuff-you-might-not-know-you-can-do.152021/