Giter Site home page Giter Site logo

understandinges6's Introduction

Understanding ECMAScript 6

by Nicholas C. Zakas

Creative Commons License

ECMAScript 6 represents the biggest change to the core of JavaScript in the history of the language. Not only does the sixth edition add new object types, but also new syntax and exciting new capabilities. The result of years of study and debate, ECMAScript 6 reached feature complete status in 2014. While it will take a bit of time before all JavaScript environments support ECMAScript 6, it's still useful to understand what's coming and which features are available already.

This book is a guide for the transition between ECMAScript 5 and 6. It is not specific to any JavaScript environment, so it is equally useful to web developers as it is Node.js developers.

What you'll learn:

  • All of the changes to the language since ECMAScript 5
  • How the new class syntax relates to more familiar JavaScript concepts
  • Why iterators and generators are useful
  • How arrow functions differ from regular functions
  • Additional options for storing data using sets, maps, and more
  • The power of inheriting from native types
  • Why people are so excited about promises for asynchronous programming
  • How modules will change the way you organize code

Where to Read

The published version is available for free and contains the latest "blessed" version. The content may be incomplete but should be correct. New releases are published several times a month.

Anything that is not present in the published version is considered a work-in-progress and may be incomplete or incorrect.

Purchasing an Ebook Copy

You can purchase a copy of this ebook through Leanpub. If you purchase a copy before the ebook is finished, you will receive all updates to the ebook as they are released, up to and including the finished version.

Purchasing a Print Copy

Understanding ECMAScript 6 is being printed by No Starch Press and you can purchase a print copy on Amazon. The print version is professionally copyedited and laid out.

Supporting the Author

If you enjoy this book and would like to support my efforts to create more content, there are a couple ways to do so:

A small donation is greatly appreciated and will allow me more time to continue my work.

Contributions

Even though this book is being developed in the open, the project works differently than open source software projects. Please read the following thoroughly before attempting to contribute.

Leanpub Markdown

Leanpub uses a specific flavor of Markdown for its source files. Please be sure to read their documentation about what is allowable and what is not.

Note: It may be frustrating, Leanpub does not support all of GitHub-flavored markdown.

Pull requests

Pull requests will be accepted only for correction of content and not for creation of content. Acceptable pull requests:

  • Typo fixes
  • Grammar/spelling errors
  • Alternate descriptions
  • Clarifying phrases

Pull requests that will not be considered:

  • New sections of content
  • New chapters

Basically, you can use pull requests to fix what is already in the repository but not to add what is not in the repository.

Note: An accepted pull request means that your name will be added to a list of contributors. You are still bound by the conditions of the license, meaning that you are not considered an author or owner of the content once it has been merged in. It is considered a donation of your effort to this work.

Issues

Issues can be used both to point out errors as well as to make suggestions. Use issues for:

  • Asking questions about the content
  • Pointing out an error or problem with the content
  • Requesting more information about a section
  • Suggesting a new topic for inclusion

Any issue that remains open will be addressed. Issues will be closed either when addressed or if the issue will not be addressed.

Issues should not be used for:

  • Asking when a particular section or chapter will be complete
  • Anything already marked as "TODO" in the files

These types of issues will simply be marked as invalid and closed without comment.

Copyright and License

Copyright 2014-2016 Nicholas C. Zakas.

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Frequently Asked Questions

When will the book be finished?

The book is content-complete as of June 10, 2016.

If I buy a copy now, do I get the finished one?

Yes. When you buy the Leanpub ebook today, you will automatically get all updates for the ebook. You'll be notified of updated versions via email after purchase.

How often is the book published?

Roughly every week or two the changes in GitHub are published to Leanpub.

What is the state of content in GitHub?

Everything in GitHub is a work in progress. Those parts that are known to be correct and fully-formed enough to be valuable are published to Leanpub. That's why there's more content in GitHub than is available on Leanpub, as GitHub contains everything, including content that's not quite ready for the book.

What is the difference between the print version and the Leanpub version?

The topics covered, and the order in which those topics are covered, are exactly the same between the print and Leanpub versions. The only real differences are in some words and phrases that have been altered by the copyeditors either for clarity or to follow No Starch's style guide. These changes are not backported into Leanpub because they happen on PDFs and sometimes opaquely, making it difficult to keep the two versions in sync.

Can I acquire translation rights?

Yes. Please contact No Starch Press for acquiring translation rights.

understandinges6's People

Contributors

alexyans avatar beizhedenglong avatar blacktail avatar bruha avatar craigmichaelmartin avatar denysdovhan avatar getify avatar hasdavidc avatar jakub-g avatar k4p7 avatar kavun avatar kwasniew avatar lin-credible avatar lonniebiz avatar marian-r avatar nponiros avatar nzakas avatar pbakondy avatar psalaets avatar restlessdesign avatar robertd avatar robinpokorny avatar ronen-e avatar rsmeral avatar rwaldron avatar shaunhickson avatar shmck avatar smfoote avatar stommepoes avatar yangsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

understandinges6's Issues

Please explain backward compatibility with ES5

I don't understand how exactly ES6 is compatible with ES5. For example in ES5 I can write this valid code:

var let = 1

But that would be invalid in ES6. At least in Node with --harmony I get this:

var let = 1; console.log(let)
    ^^^
SyntaxError: Unexpected token let
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:456:26)
    at evalScript (node.js:536:25)
    at startup (node.js:80:7)
    at node.js:906:3

03-Objects.md - Computed Property Names - example incorrect

The final example is incorrect:

var suffix = " name";

var person = {
    ["first" + suffix]: "Nicholas",
    ["last" + suffix]: "Zakas"
};

console.log(person["first name"]);      // "Nicholas"
console.log(person[lastName]);          // "Zakas"

In the last line there is no variable lastName in scope.

Redeclaration with let statement won't raise error

In the Let declarations part, you mentioned that if I declared a variable with var and then redeclare it with let, it will raise error. But actually it doesn't. I ran the following code in latest v8 (harmony mode), which turned out to be just fine.

> var test = 1;
> let test = 1;

What will actually raise the error is declaring two variables with same name with let in the same scope. For example:

> let test = 1;
> let test = 2;
SyntaxError: Variable 'test' has already been declared
    at Object.exports.createScript (vm.js:44:10)
    at REPLServer.defaultEval (repl.js:118:23)
    at bound (domain.js:255:14)
    at REPLServer.runBound [as eval] (domain.js:268:12)
    at REPLServer.<anonymous> (repl.js:277:12)
    at REPLServer.EventEmitter.emit (events.js:104:17)
    at REPLServer.Interface._onLine (readline.js:202:10)
    at REPLServer.Interface._line (readline.js:531:8)
    at REPLServer.Interface._ttyWrite (readline.js:806:14)
    at ReadStream.onkeypress (readline.js:101:10)

Provide some clarity around the naming of Object.assigns

I found the following paragraph to be a little bit confusing.

This pattern became popular enough that ECMAScript 6 added Object.assign(), which behaves the same way. The difference in name is to reflect the actual operation that occurs. Since the mixin() method uses the assignment operator (=), it cannot copy accessor properties to the receiver as accessor properties. The name Object.assign() was chosen to reflect this distinction.

I think I got confused, because the implication was that Object.assign() was specifically not called mixin() because of the assignment operator. I've read through a lot of stuff and I've seen a lot about Object.define() and Object.mixin(), but not anything specifically saying that mixin() was not used as the name because of the assignment operator (not that this isn't the case, just that it's hard to find).

I thought maybe it could be stated more clearly if it was written like this:

This pattern became popular enough that ECMAScript 6 added Object.assign(), which behaves the same way. It was given to the name Object.assign to reflect the fact that it uses the assignment operator (=) to transfer properties.

Error in README.md

In this file there is a line that reads:
"All of the changes to the language since ECMAScript 6"
I think this should be ES 5.

Let declarations are not "hoisted"

Or rather, they are, but there's a temporal dead zone introduced so that using them before declaration results in a ReferenceError (not undefined). The examples in "The Basics" are wrong in this regard, as is the advice to manually hoist them to the top of the block.

Are Generators Asynchronous?

When I yield is there any sort of enforcement of async behavior? I think the answer is no, because otherwise the for..of would do weird things, but I kept thinking about this question as I read the section.

Here's maybe a different take on that question:

What happens if I yield in the middle of an async operation?

function *doSomethingCrazy() {
   fs.readFile('toast.txt', function(data) {
        yield data;
   });
}

Typo in Symbol chapter

the line "“Only applied with with statement object records - does not refer to other scopes.”

Should be "Only applied with the with statement".

02-Functions, Arrow Function sections order question

Reading through "Arrow Function" sections, I noticed that after the first section with the PageHandler example, there is a following section that does a deep-dive on Arrow syntax, but then a "usage" section appear, which looks almost identical to the first section.

Minor typo regarding the value of a lastIndex variable during the explanation of the `y` regular expression flag.

There seems to be a minor error during the explanation of the y regular expression flag and the lastIndex method associated with a correctly instantiated of an object whose Constructor is RegEx in ES5 on browser's that's not Firefox.

The following code snippet was being discussed regarding the behavior of the lastIndex method yet the wrong number is seemingly mentioned in the following paragraph about its intent prior to discussing the behavior and implications of the y regular expression flag being standardized:

var pattern = /hello\d\s?/g,
    text = "hello1 hello2 hello3",
    result = pattern.exec(text);

console.log(result[0]);     // "hello1 "

pattern.lastIndex = 7;
result = pattern.exec(text);

console.log(result[0]);     // "hello2 "

After this code snippet, it is stated that the last index value above was correct towards starting the regular expression match with a lastIndex value of 6 instead of 7.

Even taking account zero-based numbering, this seems to be a typo.

The Rest Parameter example could be different

I would like to propose changing the Rest Parameter example function.

A function like underscore's pick is a perfect example in my opinion

function pick(object, ...keys){
   let result = Object.create(null);
   for(let i = 0; i < keys.length; i++){
      let key = keys[i];
      result[key] = object[key];
   } 
   return results
}

I think current example is not demonstrating a very good use case of the feature.

Clear up let behavior

In regards to

if (foo) {
    console.log(bar);
    let bar = "foo"
}

The console.log() will throw an error in strict mode but will return undefined in sloppy mode.

The relevant spec algorithm is GetBindingValue, per step 3.a undefined is returned sloppy mode.

for-of and array-likes

The following statements from 06-Iterators-And-Generators.md:

Because the statement works with any array like values, you can also use it on objects such as arguments and DOM NodeList objects (neither of which have the forEach() method):

Is incorrect—for-of works with iterables (any object that implements the iterator interface by defining a computed property whose value is the custom or default iterator), not array-likes. Thankfully, arguments will have this by default, but it's not clear what the timeline for NodeList is, so Array.from would still be necessary:

var divs = document.getElementsByTagName("div");

for (let div of Array.from(divs)) {
  div.innerHTML = "Processed...";
}

Of course, when/if NodeList is specified with an iterator and the implementation is in place, then your current example will work.

Anyway, important to note that it won't work with any array-like.

Object.assign with getters and setters

I'm not 100% sure about this but my understanding is that Object.assign is acting different for getter and setter methods.

For example

var receiver = {};
var obj = {
  set foo(f){
    console.log('set');
  },
  get foo(){
    return 'foo';   
  }
}

Object.assign(receiver, obj);

receiver.foo = 1; // This should log "set"

var simpleAssign = {};
simpleAssign.foo = obj.foo;
simpleAssing.foo = 1; // This will not log "set"

I couldn't make sure about this in docs.

If that's the case then maybe it worth mentioning in Object.assing section

Formatting on iphone.

Photo taken from iPhone 5: if possible consider reformatting to show indentation clearer.
photo 29-11-2014 17 33 38

Object.assign() - mention similarity to _.extend()?

Since so many people use Underscore.js and jQuery and they call their mixin() methods extend(), it might be useful to mention the word "extend" as a synonym of "mixin" in the Object.assign() discussion.

(I guess mentioning specific libraries might complicate the discussion too much, since although the Underscore one is totally equivalent to Object.assign(), the jQuery one isn't due to supporting deep copy).

03 - Objects sentence on line 139 is not as clear as it could be

Original sentence:
Anything you would be inside of square brackets while using bracket notation...

Although I understand from the context what you want to say, I think the '...you would be inside...' part could be reformulated to be made more clear.

Possible changed sentences:
Anything you put inside of square brackets while using bracket notation...
or
Anything you write inside of the square brackets while using bracket notation...

Regarding ES6 implementation of super

Just curious: @nzakas , do you think super could have been better implemented in ES6 if it only referred to the method of the super class of the same name as the method it's used in instead of the entire superclass?

As @jashkenas noted a year ago in an interesting [feature request] he had to deal with (jashkenas/coffeescript#2638), it seems the current implementation of super would enable what some may call an encapsulation violation.
An example of this I've demonstrated below:

class bar extends foo { 
  es6_method(){
   return super.someOtherMethod(1, 2, 3);

  } 
} 

Overall, what's your thoughts on the ES6's super as it is today to allow such behavior potentially with the "final" version of the specification?

Avoid arrow function in Basics section

As arrow functions aren’t introduced until the next chapter, it may be more appropriate to alter:

var normalized = values.map(text => text.normalize());

to its ES5 equivalent (for readers who are just starting out with ES6):

var normalized = values.map(function(text) {
  return text.normalize();
});

Typo/Grammatical error in Better Unicode Support paragraph.

Found a typo/grammatical error.

I've never submitted an issue on an eBook before, so my apologies if this is too nitpick-y.

"These globally unique identifiers are called code points are simply numbers starting at 0"

Perhaps you mean:

"These globally unique identifiers [which|that] are called code points are simply numbers starting at 0"

Harmony

Work then began on ECMAScript Harmony, which then became ECMAScript 6

I think that Harmony refers to everything that happened after the ES4 debacle (so ES5, 6, 7, etc.). Brendan Eich will know better.
The idea being that the consensus among TC39 has to be "harmonuous" to eventually lead to an actual standard one day (and it didn't seem like it was the case between ES3 and 4)

Chapter01 code example review

Just going through the code examples and verify they work as advertised.

  • String.prototype.codePointAt() does not accept character positions, but code unit positions:
js> "𠮷a".codePointAt(0)
134071
js> "𠮷a".codePointAt(1)
57271
js> "𠮷a".codePointAt(2)
97
  • The supportsExtendedEscape() example code needs to use eval (or Function), otherwise pre ECMAScript 6 environments won't even parse the function code.
function supportsExtendedEscape() {
    try {
        eval('"\\u{00FF1}"');
        return true;
    } catch (ex) {
        return false;
    }
}
  • There is extra whitespace in the third RegExp sticky example:
console.log(result[0]);             // "hello1 "
console.log(pattern.lastIndex);     // 6

It should read "hello1" instead of "hello1 ".

  • There is an extra closing curly brace in the let for-loop example and the expected output is wrong:
for (var i=0; i < 10; i++) {}   // <- HERE
     funcs.push((function(value) {
         return function() {
             console.log(value);
         }
     }(i)));
 }

for (let i=0; i < 10; i++) {}  // <- HERE
     funcs.push(function() { console.log(i); });
 }

The output of the var + for-loop is 10 ten times instead of 11 ten times.
The output of the let + for-loop is 0...9, not 1...10.

  • Access to uninitialized let-scoped variables is only a ReferenceError in strict mode, in sloppy mode the example will print undefined:
if (condition) {
    console.log(value);     // ReferenceError!
    let value = "blue";
}
  • The var+let redeclaration example could emphasize that a redeclaration is not a runtime but instead an early error while parsing the code:
var count = 30;

// Parser throws a SyntaxError
let count = 40;

Reference extend in Object.assign section

Many JavaScript libraries have a mixin method similar to this:

This is essentially #99 again, so sorry if this isn't what you meant, but I thought it might be clearer to say 1 of these 2:

  • Many JavaScript libraries have a mixin or extend method similar to this:
  • Many JavaScript libraries have a mixin method similar to this (often with the name extend):

gitbook integration

Hello!
What do you think about http://www.gitbook.io/ integration ?

es6

I did init commit 6c22468 in my fork, to be able to read it from gitbook node.js server.

I can move contents to gh-pages branch and make PR, so your book will be easier to reach and read, if you find this interesting.

Thanks!

Typo in chapter 1

In the sentence "In this code, the constant MAX_ITEMS is declared within and if statement" "and if" should be "an if".

Combination of default values & destructured parameters

It seems possible to use destructured parameters and default values at the same time and I think you should add one example of this kind in the book.

Instead of something like this in ES5:

function myFunc(options) {
   options = options || {};
   var params1 = options.params || 'default_value_1';
   var params2 = options.params || 'default_value_2';
   // ...
}

it should be possible to use default values & destructured parameters at the same time in ES6:

function myFunc({ params1 = 'default_value_1', params2 = 'default_value2' }) {
   // ...
}

Here's an example from here:

let doWork = function({firstName, lastName, role="developer"}) {
    return role + " " + firstName + " " + lastName;
};

let person = {firstName: "Scott", lastName: "Allen"};
let result = doWork(person);

expect(result).toBe("developer Scott Allen");

However I don't know if it's still required to add a default value for the whole object:

function myFunc({ params1 = 'default_value_1', params2 = 'default_value2' } = {}) {
   // ...
}

Github Markdown Syntax

In this book, I saw too much 'Github Flavored Markdown' syntax error.
Should use

|  ```js
|     var a = 4;
|     console.log(a);
|  ```

instead of

|
|  {lang=js}
|      var a = 4;
|      console.log(a);
|

And, thanks for your amazing books.

`codePointAt`

[codePointAt] accepts the character position (not the code unit position)

This is incorrect — it’s the other way around (unfortunately).

'a𝌆b'.codePointAt(0) == 'a'
'a𝌆b'.codePointAt(1) == '𝌆'
'a𝌆b'.codePointAt(2) == '\uDF06'
'a𝌆b'.codePointAt(3) == 'b'

Is the /g/ regular expression flag also sticky by default without the need for the /y/ regular expression flag?

It maybe an issue with the es6fiddle compiler itself, but the g seems to be sticky without the y flag:

// y is an invalid flag for es6 fiddle? 
var pattern = /hello\d\s?/g, text = "hello1 hello2 hello3", result = pattern.exec(text);

console.log(result[0]); // hello1 
console.log(pattern.lastIndex); // 7 

//pattern.lastIndex = 7; 
result = pattern.exec(text); 
console.log(result[0]);
console.log(pattern.lastIndex); // 14 

Based on the console output of http://www.es6fiddle.net/hua5z36s/ , is the /g regular expression sticky as well, I was mistaken all along that it isn't sticky as well, or is it a bug I get the same result as the y regular expression flag?

Cover the well-known symbols

  • Symbol.hasInstance
  • Symbol.isRegExp
  • Symbol.toStringTag
  • Symbol.iterator
  • Symbol.unscopables
  • Symbol.toPrimitive
  • Symbol.isConcatSpreadable

03-Objects.md - Method Initializer Shorthand

This text could do with some clarification as to whether the resulting function is anonymous or not.

The syntax looks just like a named function declaration but without the function keyword, at which point one might expect the given name to be available within the function's own scope.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.