ES6 Javascript

This is some note from the Udemy course: ES6 Javascript: The Complete Developer's Guide

Array Helper Method

forEach: take place of for loop, function is iterator function

colors.forEach(function(color) {
    console.log(color);
}); 
function adder(number) {
    sum += number;
}
numbers.forEach(adder);

map

var numbers = [1,2,3];
var doubled = numbers.map(function(number) {
    return number * 2;
});

filter (should return boolean)

products.filter(function(product) {
    return product.type === 'vegetable' 
        && product.price < 10;
})

var numbers = [1,2,30];
var lessThanFive = reject(numbers, function(item) {
    return item >= 5;
});
function reject(array, iteratorFunction) {
  return array.filter(function(number){
      return !iteratorFunction(number);
  });
}

find: will break the loop once the iterator function returns true (should return boolean)

users.find(function(user) {
    return user.name === 'Alex';
});

every (should return boolean)

computers.every(function(computer) {
    return computer.ram > 16;
})

some (should return boolean)

computers.some(function(computer) {
    return computer.ram > 16;
})

reduce: condensing the whole array into a single value

  • here, 0 is an initial value
  • the first parameter of the passed function has an accumulative state of values, which has the same type of the initial value
  • the second parameter is every single value in the numbers array
  • return changed value at the end
numbers.reduce(function(sum, number) {
    return sum + number;
}, 0)
  • check balanced parameters
  • if the final sum result is 0, it is balanced
  • if '(', we add one to previous
  • if ')', we reduce one to previous
  • if not parenthesis, return the same value
  • if negative, return the same value so that finally the sum won't be true. negative means the parenthesis is out of order
function balanceParens(string) {
    return !string.split("").reduce(function(previous, char) {
      if (previous < 0) { return previous; }
      if (char == '(') { return ++previous; }
      if (char == ')' { return --previous; }
      return previous;
    }, 0)
}

Const and Let

  1. const = var that never changes
  2. let = var that is variable

Template Strings

之前我們要用引號把變量和string分開,現在用一個backstick(`),我們可以將變量和string都包括在backstrick里面,用${}把變量給圍起來,還可以對它進行運算。

"This year is " + year
---
`The year is ${year + 2}`

Arrow Functions

Replace function to a fat arrow

const add = function(a, b) {
    return a + b;
}
=================================
const add = (a, b) => {
    return a + b;
}
=================================
// 因為在{}中只有一個return statement, we can further simplify it into
// implicit return
const add = (a, b) => a + b; 
=================================
如果我們只有一個變量傳入的話,可以把括號也省了,也可以把分號(semicolon)也省了
const double = number => 2 * number
=================================
// solve binding this problem
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      var self = this;
      return this.members.map((member) =>
          return `${member} is on team ${self.teamName}` // change this to self
      });
    }
};

// use bind this
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      return this.members.map((member) =>
          return `${member} is on team ${this.teamName}`
      }.bind());
    }
};

// use lexical this
// this === team
const team = {
    members: ['Jane', 'Bill'],
    teamName: 'Super Sqad',
    teamSummary: function() {
      return this.members.map((member) =>
          return `${member} is on team ${this.teamName}`
      });
    }
};

Enhanced Object Literals

function createBookShop(inventory) {
    return {
      inventory, // inventory: inventory
      inventoryValue() { // inventoryValue: function()
        return this.inventory.reduce((total, book) => total + book.price;
      }
    }
}
function saveFile(url, data) {
    $.ajax({ url, data, method: "POST"}); // url: url, data: data
}

Default Function Arguments

function makeAjaxRequest(url, method = 'GET') {}
makeAjaxRequest(url, null); // method will be set to undefined

Rest and Spread Operator

...這個東西會把一個container里的東西spread out成一個個單獨的個體,然后再將它們變為a list。

const color = ['red, 'green']
const favorite = ['orange', 'yellow']
const color2 = ['fire red']
[ 'blue', ...color, ...favorite, ...color2] => ['red, 'green', 'orange', 'yellow', 'fire red' ]
function validateShoppingList(...items) {
  if (items.indexOf('milk') < 0) {
     return [ 'milk', ...items];
  }
  return items;
}

Destructuring

我們所要創建的變量和要引用的變量名字必須一致。
You can pull a variable of an object(use {})or an array(use []) which would reduce the amount of code you have to write!

var expense = {
    type: 'Business',
    amount: '$45 USD'
};

// I want to create a new variable type, which refers to expense.type property
const { type } = expense;
const { amount }  = expense;

// even simpler
const { type, amount } = expense
var savedFiled = {
    extension: 'jpg',
    name: 'repost',
    size: 14040
};

function fileSummary({ name, extension, size }, { color }) {
    return `${color} The file ${name}.${extension} is of size ${size}`;
}

fileSummary(savedFiled, { color: 'red' });
const companies = [
    'Google', 
    'Facebook',
    'Uber'
];

const [ name1, name2 ] = companies;
name1 === 'Google'  // true
name2 === 'Facebook' // true

const [name, ...rest] = companies
name === 'Google' // true
rest === ['Facebook', 'Google'] // true
const companies = [
    { name: 'Google', location: 'Mountain View' },
    { name: 'Facebook', location: 'Menlo Park' }
]

const [location] = companies;
location === { name: 'Google', location: 'Mountain View' } // true
const [{location}] = companies;
location === 'Mountain View' // true
const Google = {
    locations : [ 'Mount View', 'New York', 'London' ]
};
const { locations: [ location ] } = Google
location === 'Mount View' // true

Classes to Implement Prototype Inheritance

class Car {
    constructor(options) {
       this.title = options.title;
    }

    drive() {
        return 'vroom';
    }
}

class Toyota extends Car {
    constructor(options) {
        super(options);
        this.color = options.color;
    }
    honk() {
      return 'beep';
    }
}
const car = new Car({ title: 'Toyota' });
const t = new Toyota({ title: 'Toyota', color: 'red' });

Generators

Simple Use

function* colors() {
    yield 'red';
    yield 'blue';
    yield 'green';
}

const gen = colors();
gen.next(); // red, done:false
gen.next(); // blue, done:false
gen.next(); // green, done: false
gen.next(); // done: true

// that is the same as 
const myColors = [ ]
for (left color of colors()) {
    myColors.push(color);
}

An example to show:

  1. how values are passed in and out for yield
  2. how return statements are used in the generator, and why it is not the best choice (in for...of loop, it will throw away the return statement, while in the generator iterator(.next()), it won't)
function *foo(x) {
    var y = 2 * (yield (x + 1));
    var z = yield (y / 3);
    return (x + y + z);
}

var it = foo( 5 );

// note: not sending anything into `next()` here
// what we sent in is the return place for the last yield
console.log( it.next() );       // { value:6, done:false }

// we sent in 12, which goes to the line var y = 2 * (yield(x + 1))
// it.next() will return to line var z = yield (y / 3);
console.log( it.next( 12 ) );   // { value:8, done:false }

console.log( it.next( 13 ) );   // { value:42, done:true }

Use Symbolic.iterator which is a special object to tell for...of loop how to iterate an object.

Promises

// only resolve the request after 3000ms
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, 3000);
});

// the most common usage
url = "https://www.abc.com"
fetch(url) // this will return a promise
    .then(response => response.json())
    .then(data => console.log(data)) // json data
    // a big pitfall: it doesn't catch errors of 404, because it has actually reach the server and return a failed status code. Only when the request can't reach a server will an error be caught.
    .catch(error => console.log('BAD', error));

promise
    .then(() => console.log('appear after resolved'))
    .then(() => console.log('a chain of then!'))
    .catch(() => console.log('uh oh!! something bad happens'));
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容