From Learncode YouTube: Part 1, Part 2
- babeljs.io - most mainstream
- Traceur - competitor
var foo = {
bar: 1,
baz: 2
};
var bar = foo.bar;
var baz = foo.baz;
var {bar, baz} = foo;
var tenses = ["me", "you", "he"];
var firstPerson = tenses[0];
var secondPerson = tenses[1];
var [ firstPerson, secondPerson ] = tenses;
Tip: Leave spaces around {} and [] to give visual cue that it's destructuring.
Promise.all([promise1, promise2]).then(results) {
var results1 = results[0];
var results2 = results[1];
}
Promise.all([promise1, promise2]).then([ results1, results2 ]) {
console.log(results1);
}
var foo = 2;
var obj = {
bar: 1,
foo: foo
};
var foo = 2;
var obj = {
bar: 1,
foo
};
var name = "dave";
var age = 92;
some.method({
name: name,
age: age
});
some.method({ name, age });
Note: Not as commonly used
var name = "dave";
var obj = {};
obj["name" + name] = "some value";
var obj = {
["name" + name]: "some value"
};
Very useful
function calculateBmi(weight, height) {
var bmi = weight / Math.pow(height, 2);
if (bmi > max) {
console.log("you're overweight);
};
if (callback) {
callback(bmi);
};
};
calcBmi({ weight, height, max: 25 });
calcBmi({ weight, height, callback: function(){} });
Old: needed to use opts object in fn. Now you don't need it
Order no longer matters
| Old way | New way |
|---|---|
function calcBmi(max) { if (typeof max === 'undefined') max = 25;}; |
function calcBmi({ max = 25 }){}; |
function calcBmi({ height: h }){
console.log(h);
};
Very useful
var name = "dave";
var greet = "hi, my name is " + name + " and I like to " + action + ".";
// multiline is ugly
var greet = "hi, my name is\n" +
name +
"and I like to\n" +
action;
var greet = `hi, my name is ${name} and I like to ${name}`;
// multiline
var greet = `hi, my name is ${name}
and I like to
${action}`;
Note: Atom editor has better default ES6 syntax highlighting comapred to Sublime
Let is the new var
if (true) {
let b = 2;
};
// also can use in for, while
const is same as let, in that it's block scope
const cannot be overwritten. Bar as an object can be mutated however.
Use const for everything when possible. Shouldn't have to change values of things. If you do need to, use let.