Featured image of post 【JavaScript Cheesheet】ES6

【JavaScript Cheesheet】ES6

【JavaScript Cheesheet】ES6

Photo by Mohammad Rahmani on Unsplash

基礎 Basic

Template Strings

const message = `Hello ${name}`

const str = `
hello
the world
`

Binary and octal literals

let bin = 0b1010010
let oct = 0o755

Exponential Operator

const byte = 2 **8

新函式庫 New library additions

New string methods

"hello".repeat(3)
"hello". includes("ll")
"hello". startsWith("he")
"hello".padStart(8)     // "hello"
"hello".padEnd(8)       // "hello"
"hello".padEnd(8, '!')  // hello!!!
"\u1E9B\u0323".normalize("NFC")

New Number Methods

Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN")         // false

New Math methods

Math.acosh(3)    // 1.762747174039086
Math.hypot(3, 4)  // 5
Math.imul(Math.pow(2, 32) -1, Math.pow(2, 32) -2) // 2

New Array methods

//return a real array
Array.from(document.querySelectorAll("*"))
//similar to new Array(...), but without the special single-argument behavior
Array.of(1, 2, 3)

私密類別 Private class

The javascript default field is public (public), if you need to indicate private, you can use (#)

class Dog {
  #name;
  constructor(name) {
    this.#name = name;
  }
  printName() {
    // Only private fields can be called inside the class
    console.log(`Your name is ${this.#name}`)
  }
}

const dog = new Dog("putty")
//console.log(this.#name)
//Private identifiers are not allowed outside class bodies.
dog.printName()

Static private class

class ClassWithPrivate {
  static #privateStaticField;
  static #privateStaticFieldWithInitializer = 42;

  static #privateStaticMethod() {
    // …
  }
}

Promises

make the commitment

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})

Using Promises in finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => {
    /*logic independent of success/error */
  })

Promise function

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

Async-await

async functions are another way to use functions. See: Async Function

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}

解構資料 Destructuring

Destructuring assignment

// Arrays
const [first, last] = ['Nikola', 'Tesla']

// Objects
let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

Defaults

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores

//Result:
//math === 22, sci === 33, arts === 50


function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}

greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Function parameters

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}

greet({ name: 'Larry', greeting: 'Ahoy' })

Reassign keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })

Loop

or (let {title, artist} of songs) {
  ···
}

Object Deconstruction

const { id, ...detail } = song;

Spread operator

Object Extensions

// with object extensions
const options = {
  ...defaults,
  visible: true
}

// No object extension
const options = Object.assign(
  {}, defaults,
  { visible: true })

Array Expansion

// with array extension
const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
// No array expansion
const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

函式 Functions

Function parameters

// Default parameters
function greet (name = 'Jerry') {
  return `Hello ${name}`
}


// Rest parameters
function fn(x, ...y) {
  // y is an array
  return x * y.length
}



// Extensions
fn(...[1, 2, 3])
//same as fn(1, 2, 3)

Arrow function

// Arrow functions
setTimeout(() => {
  ···
})


// with parameters
readFile('text.txt', (err, data) => {
  ...
})


// implicit return
arr.map(n => n*2)
//no curly braces = implicit return
//Same as: arr.map(function (n) { return n*2 })
arr.map(n => ({
  result: n*2
}))
//Implicitly returning an object requires parentheses around the object

參數預設值 Parameter setting default value

function log(x, y = 'World') {
  console.log(x, y);
}

log('Hello') // Hello World
log('Hello', 'Taiwan') // Hello Taiwan
log('Hello', '') // Hello

Used in conjunction with destructuring assignment defaults

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() // undefined 5

name attribute

function foo() {}
foo.name // "foo"

物件 Objects

Shorthand Syntax

module.exports = { hello, bye }

// same below:
module.exports = {
  hello: hello,
  bye: bye
}

method

const App = {
  start () {
    console.log('running')
  }
}

//Same as: 
const App = { 
  start: function () {···} 
}

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}

Computed property name

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
//Same as: handlers = { 'onclick': true }

取得資料 Extract value

const fatherJS = { age: 57, name: "Zhang San" }
Object.values(fatherJS)
//[57, "Zhang San"]
Object.entries(fatherJS)
//[["age", 57], ["name", "Zhang San"]]

模組 Modules

Imports import

import 'helpers'
//aka: require('···')

import Express from 'express'
//aka: const Express = require('···').default || require('···')

import { indent } from 'helpers'
//aka: const indent = require('···').indent

import *as Helpers from 'helpers'
//aka: const Helpers = require('···')

import { indentSpaces as indent } from 'helpers'
//aka: const indent = require('···').indentSpaces

Exports

export default function () { ··· }
//aka: module.exports.default = ···

export function mymethod () { ··· }
//aka: module.exports.mymethod = ···

export const pi = 3.14159
//aka: module.exports.pi = ···


const firstName = 'Michael';
const lastName = 'Jackson';
const year = 1958;
export { 
  firstName, 
  lastName, 
  year
};

export *from "lib/math";

as keyword renaming

import {
  lastName as surname // import rename
} from './profile.js';

function v1() { ... }
function v2() { ... }

export { v1 as default };
//Equivalent to export default v1;

export {
  v1 as streamV1, // export rename
  v2 as streamV2, // export rename
  v2 as streamLatestVersion // export rename
};

Dynamically load modules

button.addEventListener('click', event => {
  import('./dialogBox.js')
    .then(dialogBox => {
      dialogBox. open();
    })
    .catch(error => {
      /*Error handling */
    })
});

import() allows module paths to be dynamically generated

onst main = document.querySelector('main')

import(`./modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });

import.meta

ES2020 Added a meta property import.meta to the import command, which returns the meta information of the current module

new URL('data.txt', import.meta.url)

In the Node.js environment, import.meta.url always returns a local path, that is, a string of the file:URL protocol, such as file:/// home/user/foo.js

Import Assertions

// static import
import json from "./package.json" assert {type: "json"}
//Import all objects in the json file


// Dynamic Import
const json = await import("./package.json", { 
  assert: { 
    type: "json" 
  } 
})

產生器 Generators

Generator function

function*idMaker () {
  let id = 0
  while (true) { yield id++ }
}

let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2

For..of + iterator

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // truncate sequence at 1000
  if (n > 1000) break;
  console.log(n);
}

Relationship with Iterator interface

var gen = {};
gen[Symbol.iterator] = function*() {
  yield 1;
  yield 2;
  yield 3;
};

[...gen] // => [1, 2, 3]

Symbol.iterator property

function*gen() { /*some code */}
var g = gen();

g[Symbol.iterator]() === g // true

Reference

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy