ES6: Difference between revisions

From Bitpost wiki
No edit summary
Line 1: Line 1:
ES6 brings lots of syntactic sugary goodness.  I'll also add other niceties here too even if not strictly ES6.
==== Arrow functions ====
==== Arrow functions ====
Simplified functions that have no this pointer.
Simplified functions that have no this pointer.
Line 22: Line 24:
* Deeper destructure:
* Deeper destructure:
  const nameChange = ({ target: { value }}) => setName( value );
  const nameChange = ({ target: { value }}) => setName( value );
==== Backtick strings ====
Any time you have to build strings using variables, use backtick:
const title = `My name is ${name}.  I can use "quotes" and 'single-quotes' all day.`;
But silly ESlint will bitch if you use them for string literals.  Ok fine!
const desc = 'Use single-quotes if you don\'t need variables, if you want to make eslint happy.';

Revision as of 13:35, 20 September 2020

ES6 brings lots of syntactic sugary goodness. I'll also add other niceties here too even if not strictly ES6.

Arrow functions

Simplified functions that have no this pointer.

const myfunc = onevar => {
   console.log( onevar );
};

const myfunc = ( v1, v2 ) => {
   console.log( `v1 = ${v1}, v2 = ${v2}` );
};

// One liners are simple, no curly braces or return statement needed:
const doubleIt = onevar => onevar * 2;

Destructuring

  • Destructure internal variables with curly braces on left side:
const { internalprop1, prop2 } = myobj;
  • Arrow + destructure:
const myFuncThatTakesOneObjectParam = ({ id, name, desc }) => {
  console.log( id, name, desc );
};
myFunc( { id: 2, name: 'internal name', desc: 'My desc' } );
  • Deeper destructure:
const nameChange = ({ target: { value }}) => setName( value );

Backtick strings

Any time you have to build strings using variables, use backtick:

const title = `My name is ${name}.  I can use "quotes" and 'single-quotes' all day.`;

But silly ESlint will bitch if you use them for string literals. Ok fine!

const desc = 'Use single-quotes if you don\'t need variables, if you want to make eslint happy.';