Eric Ponto | @ericponto
var x = 10; // good ol' var
let y = 10; // block scoped
const MY_NUMBER = 10; // can't change it
function test() {
var x = 10;
if (true) {
let x = 15;
}
console.log(x); // 10
}
for (let i = 0; i < 100; i++) {}
console.log(i); // undefined
const x = 100;
x = 5; // error
var stuff = [10, 20];
var [x, y] = stuff;
console.log(x); // 10
console.log(y); // 20
The old way
var temp = x;
x = y;
y = temp;
The new way
[x, y] = [y, x];
var a = 5;
var b = 6;
var c = {a, b};
console.log(c.a); // 5
console.log(c.b); // 6
var {x, y} = {x: 10, y: 20};
console.log(x); // 10
console.log(y); // 20
var x = [2, 3, 4];
var y = [1, ...x, 5] // [1, 2, 3, 4, 5]
var z = [1];
z.push(...x); // [1, 2, 3, 4]
var fn = function(a, b, c) {};
var x = [1, 2, 3];
// old way
fn.apply(null, x);
// new way
fn(...x);
function fn() {
Array.isArray(arguements); // false
}
function fn(...args) {
Array.isArray(args); // true
}
function fn(a, b, ...others) {
// don't need to try to slice arguements any more
}
The old way
function myFunction(a, b, c) {
a = a || "default";
b = b || "bye";
c = c || "c";
}
The new way
function myFunction(a="default", b="bye", c="c") {
}
The old way
var divs = document.querySelectorAll("div");
divs.forEach(/*...*/) // error
[].forEach.call(divs, function(){});
The new way
var divs = document.querySelectorAll("div");
Array.from(divs).forEach(function() {});
var x = ["a", "b", "c"];
for (let n of x) {
console.log(n);
} // "a", "b", "c"
var x = {a: 1};
var y = {b: 2};
var o = Object.assign(x, y); // {a: 1, b: 2}
The old way
var add = function(x, y) {
return x + y
}
The new way
var add = (x, y) => x + y;
function Thing() {
this.things = [1, 2, 3];
/*this.squaredThings = this.things.map(function(x) {
return this.square(x);
}.bind(this));*/
this.squaredThings = this.things.map(x=>this.square(x)); // [1, 4, 9]
}
Thing.prototype.square = function(n) {
return n * n;
}
var myString = `this is a
multiline string
that just works`;
// basic templating
var name = "Eric";
var greeting = `Hello, ${name}`;
var x = 2;
var y = `There is ${x * 10} of those`;
The old way
"hello".indexOf("lo") > -1; // true
The new way
"hello".contains("lo"); // true
class AwesomeThing {
constructor(a) {
this.a = a;
}
method1() {}
method2() {}
}
The old way
var Dog = function() {
Animal.call(this);
};
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constuctor = Dog;
The new way
class Dog extends Animal {
constuctor() {
super();
}
}