JS: How to Convert ES5 to ES2015
Here is a guide to convert ES5 to ES2015.
〔see 2015 Features〕
Follow this checklist, in order.
Variables and Constants
Change var
to let
Change some let
to const
.
in any for-loop, put a let
for the counter variable.
Use const
as much as possible.
Functions
Remove any use of the arguments Object in function.
use function default values.
〔see Function Argument Default Value〕
use function rest parameter.
〔see Function Rest Parameters〕
If a function does not use the this
keyword
〔see this Binding〕
, change it to Arrow Function
.
Change Function Blocks into Code Blocks
Remove the outmost function block of the from
(function (){body})()
that are just for creating local variables.
Replace it with {body}
and let
.
replace all
function f () {body}
form to
const f = function () {body}
You have to do this. Because we want to wrap a {}
around our code. If you don't change function declaration into assignment form, you can't wrap the whole code into a block because
function declaration must happen only at top level.
Now, wrap whole file into a block by wrapping curly brackets {}
around it.
Dealing with Unicode
Replace
String.fromCharCode
to
String.fromCodePoint
〔see String.fromCharCode〕
〔see String.fromCodePoint〕
Replace
charCodeAt
to
codePointAt
〔see String.prototype.charCodeAt〕
〔see String.prototype.codePointAt〕
Use Map
Rewrite some data structure that use object, to use Map.
〔see the Map Object Tutorial〕
Use Set
Rewrite some data structure that use array or object, to use Set.
〔see the Set Object Tutorial〕
Use Class
Rewrite constructor functions to use the class
keyword. This would be a big complex change.
Better is to change the code to functional programing style.
〔see Class〕