drksephy / es6-cheatsheet Goto Github PK
View Code? Open in Web Editor NEWES2015 [ES6] cheatsheet containing tips, tricks, best practices and code snippets
Home Page: http://slides.com/drksephy/ecmascript-2015
ES2015 [ES6] cheatsheet containing tips, tricks, best practices and code snippets
Home Page: http://slides.com/drksephy/ecmascript-2015
I want to translate this cheatsheet to Korean. Is anyone translating?
Can you add README_ko.md
file when translating done?
In the async-await section you say "I highly recommend using them over Generators + Promises" but you don't tell why. Could you link some article or explain the reason why it's better ?
Tks
Notice the extra whitespace you end up with https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=let%20text%20%3D%20(%0A%20%20%60cat%0A%20%20dog%0A%20%20nickelodeon%60%0A)
Named Parameters ins unclear to me.
In particular:
func(a=1)
or func({a= 1})
)WeakMap generally has little to do with classes or privatizing values.
WeakMap in JavaScript is the same as WeakMap in many other languages. It's a Map, essentially a Hash keyed by references to objects, that will GC entries when nothing else holds on to the reference.
It's "weak" because it holds onto the reference "weakly". MDN has good documentation on WeakMap
A use case for WeakMap would be something like storing data associated to a particular DOM element without polluting the DOM itself. If the DOM element is cleaned up, the entry in the WeakMap is GC'ed.
@DrkSephy @richardbutler
I think I picked the wrong example (React) in my earlier PR because React is exported using commonjs.
If the module is exported in es6 syntax, then this will not work.
const testA = 'what is it';
const testB = 'okay this works';
export default { testA, testB };
import Test, { testA, testB } from './test_export';
console.log('Test is ----> ', Test);
console.log('testA is ----> ', testA);
console.log('testB is ----> ', testB);
The result of the console log is
Test is ----> { testA: 'what is it', testB: 'okay this works' }
testA is ----> undefined
testB is ----> undefined
I would propose to get rid of the react example altogether. I apologize for providing the wrong example in the first place.
Type of issue: Formatting
Breaking changes: No
Details: On line 1147, 1150 and 1173 we have extra spaces [1 tab, 2 space] at the end of line
Instead of:
function repeat(string, count) {
var strings = [];
while(strings.length < count) {
strings.push(string);
}
return strings.join('');
}
use easier example:
function repeat(string, count) {
return new Array(count + 1).join(string);
}
did not find an example along the lines of
const foo = {a: 10}
let {a, b=20} = foo
console.log(a, b) // 10, 20
Just to avoid the confusion for newcomers, I would name it ES2015 and add es6 in brackets in the description/readme.
Blocks have been in js for a long time - they’re the reason
return
{
foo: 123
}
breaks since it is interpreted as
return undefined;
{ //block
foo: //label
123; //expression
}
That being said, blocks haven’t been very useful before due to lack of block scope, but that’s not different than the earlier discussion of let
and const
Blocks don’t really do the same thing as IIFEs in enough situations to call then replacements I think. They will not limit var
declarations, but more importantly they won't limit function
declarations which will be hoisted into a higher scope
I'm fairly new to ES6 and the section of ES6 exports left me confused. On reading it's not clear to me what it is actually doing, which makes it difficult to understand why it is a best practice. It also doesn't appear similar to the CommonJS approach, even though it is stated to be similar.
Wonderful guide and overview, thanks!
A paragraph written about Symbol.iterable
A notable example of Symbol use for interoperability is
Symbol.iterable
which exists on all iterable and iterator types in ES6: Arrays, strings, generators, etc. When called as a method it returns an object with an Iterator interface.
I had been looking for Symbol.iterable
. But, I can't find anything about Symbol.iterable
.
I'm not sure.. But I think you just mistook Symbol.iterator
with Symbol.iterable
.
Thanks for gathering ES6 information. I would love to see ES6 proxy in this.
Nice job on this. I thought these are missing and would be nice to add.
The section on let
and const
doesn't mention that they are block scoped. I think that is the most significant difference to most developers.
Also, saying that let
and const
are not hoisted is too simplistic because it does not account for the Temporal Dead Zone.
In short, accessing block-scoped identifiers before they are defined is a ReferenceError
:
console.log(x);
let x = "hi"; // ReferenceError: x is not defined
This happens even when a matching identifier exists in an outer scope. The inner x
is effectively hoisted, but the result of accessing it before declaration is an Error, not undefined
.
let x = "outer";
if (true) {
console.log(x); // ReferenceError: x is not defined
let x = "inner";
}
While technically correct (you can insert them and enumerate through all the values in a Map/Set), "use any type" ignores the fact that you cannot actually query a Map for keys of any type
The most amazing part of Maps is that we are no longer limited to just using strings. We can now use any type as a key, and it will not be type-casted to a string.
let map = new Map([ ['name', 'david'], [true, 'false'], [1, 'one'], [{}, 'object'], [function () {}, 'function'] ]);
This might give people misconceptions, since it overlooks the fact that EcmaScript doesn't define equality for non-primitive values.
That is map.get({})
or map.get(function () {})
will give you back undefined
(You'd have the same problem with Array
, Date
and any other object)
For this reason, people might want to use a library that actually shoulder that burden like:
(and, as an added bonus, the structures these libs define are immutable)
Best Practice: Leave var declarations inside of legacy code to denote that it needs to be carefully refactored. When working on a new codebase, use let for variables that will change their value over time, and const for variables that will be immutable over time.
const
has nothing to do with immutability. A const
can still change its value, e.g.:
const x = {};
x.foo = 42;
The difference between let
and const
is that assignment operators can be used for let
but not const
.
This repo went around Netflix. After reading it there were a few people perhaps confused about Symbols. This is a copy-paste of my response there...
Symbol is useful for when you want to put a key on an object without trampling other keys on that object. Each created Symbol is immutable and completely unique.
Let's say I have code that wants to patch React
with some namespace Foo
. (I have no idea why I want to do this, but i do)... and I don't want the code to break if the good folks at Facebook want to add a Foo
namespace themselves:
// this will break when they update.
React.Foo = { my: 'stuff' };
// there is no way they can break this
// because they can't possibly create the Foo symbol themselves
const Foo = Symbol(); // notice Symbol and not Symbol.for
React[Foo] = { my: 'stuff' };
Another use is for interoperability points...
Say I have some library, Netflixer
. I can say "anything that has a method at key FlixIt
, which is a Symbol I'm sharing, I know I can read". In order to "share" a Symbol, you put it in a global registry by using Symbol.for(key)
to create or retrieve it.
So the third party that wants interop can do this:
myType[Symbol.for('FlixIt')] = (x) => 'myType flixed by ' + x;
and in our Netflixable type:
Netflixer.flix = (obj) => {
const flixIt = obj[Symbol.for('FlixIt')];
if (flixIt) {
flixIt('weee');
}
}
A notable example of Symbol
usage is Symbol.iterator
which should exist on any Iterable or Iterator type (Array, string, generators, etc)
How so?
Reference: 25e4c8b#diff-17043324503bc20a641fb90473de9fac
when you declare a variable with var, it will be hoisted and set value as undefined.
I think let and const are so similar but they are passed the default value 'ReferenceError'
Great work with this page, thanks.
in :
let map = new WeakMap();
let el = document.getElementById('someElement');
// Store a weak reference to the element with a key
map.set(el, 'reference');
// Access the value of the element
let value = map.get(el); // 'reference'
// Remove the reference
el.parentNode.removeChild(el);
el = null;
value = map.get(el); // undefined
if you set el = null;
the next line value = map.get(el); obvisouly gives undefined, but this does not prove it has been removed from the map ;-)
In the importing section you said:
We can also use destructuring to import a list of values from a file:
import { sumTwo, sumThree } from 'math/addition'Similar to Python, we have named imports:
import { sumTwo as addTwoNumbers, sumThree as sumThreeNumbers } from 'math/addition'
But according to this, both are named imports except the second one is using renaming. I think the correct way to use destructuring is when importing the default or wildcard. Like for 'math/addtion'
we would do
import * as addtionUtil from 'math/addtion';
const { sumTwo, sumThree } = addtionUtil;
Given the example chosen related to fetching a JSON, it might be interesting to mention fetch because it's exactly that use-case that it tries to solve. With promises :-)
The legal status of this awesome project is unclear. Could you please add the information about the license of README content. E.g. CC-BY-SA-NC, etc.
Hi!
Thanks for a great cheatsheet. I enjoyed reading it and learn a few new things :)
However, I think that getters and setters are not part of ES6 - they were introduced in ES5:
http://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#Specifications
ES6 gives us the possibility of using getters and setters in classes :)
BR,
Marcin
In the WeakMaps section there is this example:
let map = new WeakMap();
let el = document.getElementById('someElement');
// Store a weak reference to the element with a key
map.set(el, 'reference');
// Access the value of the element
let value = map.get(el); // 'reference'
// Remove the reference
el.parentNode.removeChild(el);
el = null;
value = map.get(el); // undefined
I am not sure what the last line is demonstrating. el
has been set to null
on the previous line, and wouldn't map.get(null);
always return undefined
Please provide references to discussions, articles, specs, etc. As of now, the only question that arises when I read best practices section is: "why"?
Why is block scope better than function scope (why not use var)?
Why should we replace every anonymous function with arrow function?
Because I'm pretty sure it is.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.