Git Product home page Git Product logo

modern-js-cheatsheet's People

Contributors

a1ip avatar ahangarha avatar anshumanv avatar badbart avatar chapeupreto avatar constanna avatar cynicollision avatar elfiservice avatar errorsmith avatar fejes713 avatar gh640 avatar heromayank2 avatar hontas avatar iifeoluwa avatar loliconer avatar lynnntropy avatar mbeaudru avatar melwinalm avatar mohamed3on avatar muhammadsahimbhaur avatar nickyhk4you avatar nicolapps avatar notsu avatar piperchester avatar shridhad avatar soyaine avatar trevorsayre avatar virpo avatar watersalesman avatar wwwmarcos 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

modern-js-cheatsheet's Issues

Translation request

Bonjour! Can I translate your modern-js-cheatsheet into Chinese, by pulling request a new file named readme_CN.md to your repo? Or any other way is ok. 😁😁

Please, is sample code of "this reference" in Arraw function chapter explicit?

This is the origin sample code, the result is 1.

function myFunc() {
  this.myVar = 0;
  setTimeout(() => {
    this.myVar++;
    console.log(this.myVar);
  }, 0);
}

myFunc(); // 1

And the following code has the same reuslt 1.

function myFunc() {
  this.myVar = 0;
  setTimeout(function() {
    this.myVar++;
    console.log(this.myVar);
  }, 0);
}

myFunc(); // 1

And i think use an object manner write this example maybe better? Like this:

myVar = 123;

var object= {
  myVar: 0,
  f: function () {
    setTimeout(() => {
      this.myVar++;
      console.log(this.myVar);
    }, 0);
  }
}

object.f(); // 1

And this is the comparing code:

myVar = 123;

var object= {
  myVar: 0,
  f: function () {
    setTimeout(function() {
      this.myVar++;
      console.log(this.myVar);
    }, 0);
  }
}

object.f(); // 124

'let' and 'const' get hoisted

Declarations get hoisted, including let and const.

From the documentation:

13.3.1 Let and Const Declarations

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

So variables declared with let and const are created when accessing the enclosing scope, but remain uninitialized until the code containing the actual declaration is executed.

The TDZ article linked in this cheatsheet is also mentioning this.

Constants are not variables

And therefore, calling const variables is just plain wrong. Whole section in variables refers to them this way.

Also, telling someone to declare their variable as const is just completely incorrect based on any programming principles. That might be your preference and opinion, but it's definitely not based on any programming books or recommendations.

I haven't got to read the rest, so far, but if this issue is right in the beginning, I don't want to know, what else is lurking in your manual.

Implicit VS Explicit return

/*
To do an implicit return, the code must be written in a one-line sentence.

const double = (x) => {
return x * 2; // Explicit return here
}
Since there only is a return value here, we can do an implicit return.

const double = (x) => x * 2;

*/

I think the sentence explaining the implicit return should be written:
Since there is only one line here, we can do an implicit return. Or:
Since there is only one line here, there is no need to add the return keyword.

more like a cheatsheet

This is ace, bu not really a cheatsheet as its too long form, would it be useful to actually attempt to put the same information (in short hand) on a page or couple of pages for "quick" reference? This woud probably mostly be a design challenge TBH. And happy to help

Translations branches

I wonder if it would be better if every translation had its have branch in the commit tree. In case of updating master branch, it was easier to make corrections to translations.

Translation to Chinese

Hey there! Thanks for the nice cheatsheet. Is there any chance that I can help translate it to Chinese(Traditional)?

named exports

Hi, on modules you write:

You can only name-export variables (not functions or class), so if you want to name-export a function, you have to store it in a variable before.

But on one of the examples on MDN I can see a function cube being directly exported (as opposed to what you said above that you can't export it directly):

// module "my-module.js"
function cube(x) {
  return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { cube, foo };

Can you clarify this?

`let` can be re-assigned later

A const, as well as let, declared variables are block scoped and not accessible before being assigned, but they can't be reassigned nor re-declared afterwards.

->

A const, as well as let, declared variables are block scoped, not accessible before being assigned and can't be re-declared afterwards. const also can't be reassigned later, while let can be reassigned later .

Fold detailed explanations

It's a long document, and maybe a bit more text than I would expect of a cheatsheet ;) so it would be nice to use githubs folding syntax for all detailed explanations like so:

<details>
  <summary>Click to expand</summary>
  whatever
</details>

Being clear about not (yet) standard feature

I find it dangerous to encourage people to use not yet standardized features of the language.

For example, object rest/spread is still in stage 3, but that is not mentioned in the guide.

Russian translate

Hey, I'm going to translate this wonderful cheat sheet into Russian. If someone else is going to do the same, then first check out my repository. πŸ™‚

Polish translation

Hi, I'm a pythonista who's been tinkering with JavaScript a lot lately and I would love to translate your amazing guide into Polish. I'm already halfway through.

We will miss you

Thanks Manuel for your great work in the team.
You have learn a lot here but also contributed to create great widgets used at high level of management.
Keep your motivation and willingness to work well.

FluidGrid power!

Guillaume, Jean-Max, Remi

Spelling error

Hi,

Found a spelling error at both markdown files, introduction>motivation second and third paragraph.

screen shot 2017-09-19 at 10 18 17 am

Developers, not developpers. Recommendation, not recommandation. Could be more, just skimmed through the first few parts.

Great job at the cheatsheet by the way.

Async/Await misinformation and bad practice

The Async/Await section spreads some misinformation and bad practices. It explains that try/catch must be used whenever an await expression is used, but that is not the case. For example, this snippet:

function getGithubUser(username) {
  return new Promise((resolve, reject) => {
    fetch(`https://api.github.com/users/${username}`)
      .then(response => {
        const user = response.json();
        resolve(user);
      })
      .catch(err => reject(err));
  })
}

getGithubUser('mbeaudru')
  .then(user => console.log(user))
  .catch(err => console.log(err));

is the same as:

function getGithubUser(username) {
  return fetch(`https://api.github.com/users/${username}`).then(response => response.json());
}

getGithubUser('mbeaudru')
  .then(user => console.log(user))
  .catch(err => console.log(err));

You don't need to wrap it in another Promise, fetch already returns a promise.

This snippet is really bad, which I'll explain:

async function getGithubUser(username) { // promise + await keyword usage allowed
  try { // We handle async function errors with try / catch
    const response = await fetch(`https://api.github.com/users/${username}`); // Execution stops here until fetch promise is fulfilled.
    const user = response.json();
    return user; // equivalent of resolving the getGithubUser promise with user value.
  } catch (err) {
    throw new Error(err); // equivalent of rejecting getGithubUser promise with err value.
  }
}

getGithubUser('mbeaudru')
  .then(user => console.log(user))
  .catch(err => console.log(err));

You don't need to have a try/catch block every time you have an await expression. You're already catching the error with .catch() on the last line. Any function that getGithubUser calls that throws, and any function the functions getGithubUser() calls that throws, and so on, will be caught by the last .catch(). It should be rewritten:

async function getGithubUser(username) { // promise + await keyword usage allowed
  const response = await fetch(`https://api.github.com/users/${username}`); // Execution stops here until fetch promise is fulfilled.
  const user = response.json();
  return user; // equivalent of resolving the getGithubUser promise with user value.
}

getGithubUser('mbeaudru')
  .then(user => console.log(user))
  .catch(err => console.log(err));

Additionally, the throw new Error(err); is super bad because you lose the original error type and whatever custom stack trace implementation it has. For example:

class TlsHandshakeError extends Error {}

async function throws () {
  throw new TlsHandshakeError("key mismatch");
}

async function doSomething () {
  try {
    await throws()
  } catch (e) {
    throw new Error(e);
  }
}

doSomething.catch(e => console.error(e));

The error written to console will be Error: Error: key mistmatch rather than TlsHandshakeError: key mismatch.

The above could be:

class TlsHandshakeError extends Error {}

async function throws () {
  throw new TlsHandshakeError("key mismatch");
}

async function doSomething () {
  await throws()
}

doSomething.catch(e => console.error(e)); // TlsHandshakeError: key mismatch

The code below will catch the error and not crash the application:

async function throws () {
  throw new Error("error");
}

async function step1 () {
  await throws();
}

async function step2 () {
  await step1();
}

async function step3 () {
  await step2();
}

step3().catch((err) => {
  // Error is caught here
  console.log(err); // Error: error
});

Same with the last snippet:

async function fetchPostById(postId) {
  try {
    const token = await fetch('token_url');
    const post = await fetch(`/posts/${postId}?token=${token}`);
    const author = await fetch(`/users/${post.authorId}`);

    post.author = author;
    return post;
  } catch(e) {
    throw new Error(e);
  }
}

fetchPostById('gzIrzeo64')
  .then(post => console.log(post))
  .catch(err => console.log(err));

should be:

async function fetchPostById(postId) {
  const token = await fetch('token_url');
  const post = await fetch(`/posts/${postId}?token=${token}`);
  const author = await fetch(`/users/${post.authorId}`)

  post.author = author;
  return post;
}

fetchPostById('gzIrzeo64')
  .then(post => console.log(post))
  .catch(err => console.log(err));

Update gh-page title

Need to update the jekyll theme title to the appropriate name.

  • I'm working on this.

The last console.log throw an erro

The last console.log(myVar) throw an error because myVar is not in the global variable (outside of all functions).

function myFunction() {
  let myVar = "Nick";
  if (true) {
    let myVar = "John";
    console.log(myVar); // "John"
    // actually, myVar being block scoped, we just created a new variable myVar.
    // this variable is not accessible outside this block and totally independent
    // from the first myVar created !
  }
  console.log(myVar); // "Nick", see how the instructions in the if block DID NOT affect this value
}
console.log(myVar);

Promise Execution

Hi

A promising guide I think!
I found a little mistake in https://github.com/mbeaudru/modern-js-cheatsheet#promises. You say:
a) "So it doesn't have a current state."
b) "When called, the promise body runs".

But, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

a) the promise Object is immediately in pending state after instance creation (also Promise A+ says this)
b) the executor is executed immediately during promise object construction (Promise A+ spec did not say anything about when executor is to be executed)

Project name is misleading

While I'm sure it's a good resource, people coming here looking for an actual sheet or sheet-like document (which limits the amount of information it can contain) would be disappointed. Sorry to be so pedantic, but maybe consider renaming it to guide, compendium, or something?

Edit: just read that you're calling it "guide" in the README already..

Translation to Spanish

Hey Manuel, Great job here! I would like to help with the translation to Spanish. Is that something you would be interested?

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.