JS: How to Convert ES5 to ES2015
Here is a guide to convert ES5 to ES2015.
〔see 2015 Features〕
Follow this checklist, in order.
Change 「var」 to 「let」
Change var
to let
in any for-loop, put a let
for the counter variable.
Change 「let」 to 「const」 (optional)
Change some let
to const
Use const
as much as possible.
Remove 「arguments」 object in 「function」
Remove any use of the arguments Object in function.
use
Change function declaration to function expression
If a function form
function name (params) {body}
and body
does not contain
this
, change it to arrow function, like this
const name = ((params) => {body});
Change Function Block as local variable block into code blocks
Remove the top-level function block of the from
(function (){body})()
that are just for creating local variables.
Replace it with
{body}
and
replace all var
in body to
let
Change 「function」 declaration into function expression
replace all form of
function f () {body}
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
If the string in question is ascii only or in Unicode Basic Multilingual Plane.
Replace
charCodeAt
to
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.