Version | Link |
---|---|
ECMAScript 2015 - ES2015 - ES6 | All Features List |
ECMAScript 2016 - ES2016 - ES7 | All Features List |
ECMAScript 2017 - ES2017 - "ES8" | All Features List |
ECMAScript 2018 - ES2018 - "ES9" | All Features List |
ECMAScript 2019 - ES2019 - "ES10" | All Features List |
ECMAScript 2020 - ES2020 - "ES11" | All Features List |
All fetures Referance: https://github.com/lukehoban/es6features
- Arrows are a function shorthand using the => syntax.
- An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations
- Does not have its own bindings to this or super, and should not be used as methods
- Does not have arguments,
- Not suitable for call, apply and bind methods
- Can not be used as constructors.
- Can not use yield, within its body.
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
}
- ES6 classes are a simple sugar over the prototype-based OO pattern
- JavaScript Classes are templates for JavaScript Objects.
- Use the keyword class to create a class.
- Always add a method named constructor():
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
// ES5 code
var a = 1, b = 2, c = 3;
var obj = {
a: a,
b: b,
c: c
};
// obj.a = 1, obj.b = 2, obj.c = 3
// ES6 code
const
a = 1, b = 2, c = 3;
obj = {
a
b
c
};
// obj.a = 1, obj.b = 2, obj.c = 3
// ES6 code
const
i = 1,
obj = {
['i' + i]: i
};
console.log(obj.i1); // 1
Template strings provide syntactic sugar for constructing strings
// Basic literal string creation
`In JavaScript '\n' is a line-feed.`
// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
let arr = ["John", "Smith"]
let [firstName, surname] = arr;
alert(firstName); // John
alert(surname); // Smith
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
Language-level support for modules for component definition.
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
Referance: https://github.com/daumann/ECMAScript-new-features-list/blob/master/ES2016.MD
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
let numbers = [1, 2, 3, 4];
// ES 6 before
if(numbers.indexOf(2) !== -1) { console.log('Array contains value');}
// ES 6 after
if(numbers.includes(2)) { console.log('Array contains value');}
3 ** 3 O/P: 27
let cubed = x => x ** 3;
cubed(2) // 8
class Animal {
constructor() {
this.name = "Lion"
}
age = 0;
}
That will be complied to:
class Animal {
constructor() {
this.age = 0;
this.name = "Lion";
}
}
Especially react developers can relate easily state! and initialProps!:
class Animal {
constructor() {
this.name = "Lion"
}
age = 0;
state = {
}
initialProps = {
}
}
https://github.com/daumann/ECMAScript-new-features-list/blob/master/ES2017.MD
- "async and await make promises easier to write"
- async makes a function return a Promise
- await makes a function wait for a Promise
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError.
JavaScript Object.entries() method is used to return an array of a given object's own enumerable property [key, value] pairs
var fruits = {
apple: 10,
orange: 20,
grapes: 30,
pineapple: 40
}
Object.entries(fruits);
O/P // => [ ["apple", 10], ...etc ]
for (var [key, val] of Object.entries(fruits)) {
console.log(key, val);
}
Output:
apple 10
orange 20
grapes 30
pineapple 40
Object.values lets us return an array of a given object's own enumerable property values. Note that the order is the same as provided by the for...in loop.
var fruits = {
apple: 10,
orange: 20,
grapes: 30,
pineapple: 40
}
Object.values(fruits)
O/P [10, 20, 30, 40]
var totalVegetables = Object.values(fruits).reduce((a, b) => a + b);
console.log(totalVegetables);
Output: 100
Object.getOwnPropertyDescriptors() returns all own property descriptors of a given object A property descriptor is a record with one of the
- value
- writable
- get
- set
- configurable
- enumerable
let myObj = {
property1: 'foo',
property2: 'bar',
property3: 42,
property4: () => console.log('prop4')
}
Object.getOwnPropertyDescriptors(myObj)
/*
{ property1: {…}, property2: {…}, property3: {…}, property4: {…} }
property1: {value: "foo", writable: true, enumerable: true, configurable: true}
property2: {value: "bar", writable: true, enumerable: true, configurable: true}
property3: {value: 42, writable: true, enumerable: true, configurable: true}
property4: {value: ƒ, writable: true, enumerable: true, configurable: true}
__proto__: Object
*/
var list = [
"one",
"two",
"three", // It is valid
]
const func = (a,b,c,) => {
// no error occurs
};
'1'.padStart(3, 0);
O/P: "001"
'1'.padEnd(5, 0);
O/P: "10000"
https://github.com/daumann/ECMAScript-new-features-list/blob/master/ES2018.MD
Asynchronous iteration allow us to iterate over data that comes asynchronously, on-demand. Like, for instance, when we download something chunk-by-chunk over a network. And asynchronous generators make it even more convenient.
function asyncIterator() {
const array = [1, 2];
return {
next: function() {
if (array.length) {
return Promise.resolve({
value: array.shift(),
done: false
});
} else {
return Promise.resolve({
done: true
});
}
}
};
}
var iterator = asyncIterator();
(async function() {
await iterator.next().then(console.log); // { value: 1, done: false }
await iterator.next().then(console.log); // { value: 2, done: false }
await iterator.next().then(console.log); // { done: true }
})();
Rest properties for object destructuring assignment.
let { fname, lname, ...rest } = { fname: "Hemanth", lname: "HM", location: "Earth", type: "Human" };
fname; //"Hemanth"
rest; // {location: "Earth", type: "Human"}
Spread properties for object destructuring assignment.
let info = {fname, lname, ...rest};
info; // { fname: "Hemanth", lname: "HM", location: "Earth", type: "Human" }
Promise API is extended by an optional finally block which is called in any case (after the Promise is resolved or is rejected).
function testFinally() {
return new Promise((resolve,reject) => resolve())
}
testFinally().then(() => console.debug("resolved")).finally(() => console.debug("finally"))
// resolved
// finally
https://dev.to/prabusubra/es2019-es10-features-5b14
The flat() method enables you to easily concatenate all sub-array elements of an array. Consider the following example:
arr = [10, [20, [30]]];
console.log(arr.flat()); // => [10, 20, [30]]
console.log(arr.flat(1)); // => [10, 20, [30]]
console.log(arr.flat(2)); // => [10, 20, 30]
The flatMap() method combines map() and flat() into one method. It first creates a new array with the return value of a provided function and then concatenates all sub-array elements of the array.
console.log(arr.map(value => [Math.round(value)]));
// => [[4], [20], [26]]
console.log(arr.flatMap(value => [Math.round(value)]));
// => [4, 20, 26]
This static method allows you to easily transform a list of key-value pairs into an object:
const myArray = [['one', 1], ['two', 2], ['three', 3]];
const obj = Object.fromEntries(myArray);
console.log(obj); // => {one: 1, two: 2, three: 3}
The trimStart() and trimEnd() methods are technically the same as trimLeft() and trimRight(). These methods are currently stage 4 proposals and will be added to the specification for consistency with padStart() and padEnd().
const str = " string ";
// es2019
console.log(str.trimStart()); // => "string "
console.log(str.trimEnd()); // => " string"
// the same as
console.log(str.trimLeft()); // => "string "
console.log(str.trimRight()); // => " string"
When creating a Symbol, you can add a description to it for debugging purposes. Sometimes, it’s useful to be able to directly access the description in your code.
This ES2019 proposal adds a read-only description property to the Symbol object, which returns a string containing the description of the Symbol. Here are some examples:
let sym = Symbol('foo');
console.log(sym.description); // => foo
sym = Symbol();
console.log(sym.description); // => undefined
// create a global symbol
sym = Symbol.for('bar');
console.log(sym.description); // => bar
This makes a small change to the ECMAScript specification that allows you to omit the catch binding and its surrounding parentheses:
try {
// use a feature that the browser might not have implemented
} catch {
// do something that doesn’t care about the value thrown
}
https://areknawo.com/ecmascript-2020-biggest-new-features/ https://dev.to/aryclenio/the-new-features-of-javascript-in-2020-es11-7jc
The biggest integer "usual" number type can handle is equal to 2 ** 53 - 1 or 9007199254740991. You can access this value under the MAX_SAFE_INTEGER constant.
Number.MAX_SAFE_INTEGER; // 9007199254740991
Now, with Javascript, we can import modules dynamically through variables. With that, the variables that receive the modules are able to encompass the namespaces of these modules in a global way.
import("module.js").then((module) => {
// ...
});
// or
async () => {
const module = await import("module.js");
};
let Dmodule;
if ("module 1") {
Dmodule = await import('./module1.js')
} else {
Dmodule = await import('./module2.js')
}
/* It is possible to use Dmodule. (Methods)
throughout the file globally */
Dmodule.useMyModuleMethod()
A new syntax was added allowing the export of modules similar to import that already existed, see an example below:
// Existing in JS
import * as MyComponent from './Component.js'
// Added in ES11
export * as MyComponent from './Component.js'
Optional Chaining, known to babel users, is now supported natively by Javascript
const user = {
"name": "Aryclenio Barros",
"age": 22,
"alive": true,
"address": {
"street": "Hyrule street",
"number": 24,
}
}
// Without optional chaining
const number = user.address && user.address.number
// With optional chaining
const number = user.address?.number
Now we're starting to talk about some truly new stuff! Nullish coalescing operator (??) is a new JS operator allowing basically to provide a "default value" when the accessed one is either null or undefined. Check it out:
const basicValue = "test";
const nullishValue = null;
const firstExample = basicValue ?? "example"; // "test"
const secondExample = nullishValue ?? "example"; // "example"
The Promise.AllSettled attribute allows you to perform a conditional that observes whether all promises in an array have been resolved
const myArrayOfPromises = [
Promise.resolve(myPromise),
Promise.reject(0),
Promise.resolve(anotherPromise)
]
Promise.AllSettled(myArrayOfPromises).then ((result) => {
// Do your stuff
})
Basically, if you've ever worked with RegExps before, String.matchAll() is a nice alternative to using RegExp.exec() in a while loop with the g flag enabled. That's all there's to it. It returns an iterator (not to be confused with full-blown arrays) that contains all the match results - including capturing groups.
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
const resultsArr = [...str.matchAll(regexp)]; // convert iterator to an array
resultsArr[0]; // ["test1", "e", "st1", "1"]
resultsArr[0]; // ["test2", "e", "st2", "2"]
Lastly, we've got just a minor tweak to the specs that now strictly defines the order in which the for..in loop should iterate. It was already handled pretty well by the browsers themselves, so it's just a matter of making it official.