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'));

你可能感兴趣的:(ES6 Javascript)