What is javascript ES6
- ES6 — also known as Harmony, es-next, ES2015 — is the latest finalized specification of the language
- The ES6 specification was finalized in June 2015, (hence ES2015)
- Future versions of the specification will follow the ES[YYYY] pattern, e.g ES2016 for ES7
What is Arrow Functions
Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both statement block bodies as well as expression bodies which return the value of the expression. Unlike functions, arrows share the same lexical this as their surrounding code.
- Terse way to declare a function like param => returnValue
- Useful when doing functional stuff like [1, 2, 3].map(x => x * 2)
- You can’t name arrow functions statically, but runtimes are now much better at inferring names for most methods
1
2
// e.g.
var odds = evens.map(v => v + 1);
how to use Classes in ES6
ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
What is Template Strings(Template Literals)
Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
- You can declare strings with
`
(backticks), in addition to"
and'
- Strings wrapped in backticks are template literals
- Template literals can be multiline
- Template literals allow interpolation like
`ponyfoo.com is ${rating}`
whererating
is a variable - You can use any valid JavaScript expressions in the interpolation, such as
`${2 * 3}`
or`${foo()}`
- You can use tagged templates to change how expressions are interpolated
- Add a
fn
prefix tofn`foo, ${bar} and ${baz}`
fn
is called once withtemplate, …expressions
template
is['foo, ', ' and ', '']
andexpressions
is[bar, baz]
- The result of
fn
becomes the value of the template literal - Possible use cases include input sanitization of expressions, parameter parsing, etc.
- Add a
- Template literals are almost strictly better than strings wrapped in single or double quotes
e.g1
2
var name = "node.js", time = "today";
`hi${name}, how are you ${time}?`
How to use Multi-line Strings in ES6
In ES5, we had to use one of these approaches:
1
2
var hello = 'Welcome to \n'
+ 'http://top10webjs.com';
While in ES6, simply utilize the backticks:
1
2
var hello = `Welcome to
http://top10webjs.com`;
What is Destructuring Assignment in ES6
Destructuring in the ES6 refers to the use of patterns to effectively match values to variables or properties. It’s hard to describe in words, so an example using the more common array pattern should help:
1
2
3
4
5
6
7
8
// e.g. in ES5
var data = $('body').data(), // data has properties house and mouse
house = data.house,
mouse = data.mouse;
// In ES6, we can replace the ES5 code above with these statements:
// we'll get house and mouse variables
var { house, mouse} = $('body').data();
This also works with arrays. e.g.
1
2
var [col1, col2] = $('.column'),
[line1, line2, line3, , line5] = file.split('\n')
Let v.s. Const
let
andconst
are alternatives tovar
when declaring variableslet
is block-scoped instead of lexically scoped to afunction
let
is hoisted to the top of the block, whilevar
declarations are hoisted to top of the functionconst
is also block-scoped, hoisted, and constrained by TDZ semanticsconst
variables must be declared using an initializer,const foo = 'bar'
- Assigning to
const
after initialization fails silently (or loudly – with an exception – under strict mode) const
variables don’t make the assigned value immutable1
2
3
4
5
6
7
8
9
10
11
12
13
function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// error, already declared in block
let x = "inner";
}
}
How to use Default Parameters
In ES6, we can simply supply default values for parameters in a function, like this:
1
2
3
function add(x=0, y=0) {
return x + y;
}
Iterators + For..Of
Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in
to custom iterator-based iteration with for..of
. Don’t require realizing an array, enabling lazy design patterns like LINQ.
Map, Set, WeakMap, WeakSet
Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
1 | // Sets |
what is Promises
Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})
New string functions in ES6
In ES6, the standard library has grown immensely. Along with these changes are new methods which can be used on strings, such as .includes() and .repeat(). e.g.
1
2
console.log("abcd".includes("abc")); // true
console.log("abc".repeat(3); // 'abcabcabc'
What is Proxy
Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc. e.g.
1
2
3
4
5
6
7
8
9
var foo= function () { return 'in foo()'; };
var handler = {
apply: function (receiver, …args) {
return 'in proxy';
}
};
var p = new Proxy(foo, handler);
p() === 'in proxy';
What is Modules & Module Loaders
Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model — no code executes until requested modules are available and processed.
Module loaders support:
- Dynamic loading
- State isolation
- Global namespace isolation
- Compilation hooks
- Nested virtualization
The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.