Skip to content

Instantly share code, notes, and snippets.

@paulrouget
Last active December 16, 2015 09:09
Show Gist options
  • Save paulrouget/5410678 to your computer and use it in GitHub Desktop.
Save paulrouget/5410678 to your computer and use it in GitHub Desktop.
// Arrow functions
// spec: http://bit.ly/KN3z1c
// with lexical this
var square = function(x) { return x * x }
var square = x => { return x * x }
// Default argument value
function myLog(str, prefix = "> ", suffix = "") {
console.log(prefix + str + suffix);
}
myLog("foobar"); // > foobar
myLog("foobar", "$ ") // $ foobar
// Destructuring assignment
// doc: http://mzl.la/Xed4Ua
var squareAndCube = function(x) {
return [x*x, x*x*x];
}
var res = squareAndCube(3);
var s = res[0];
var c = res[1];
// ES6:
var [s,c] = res;
// With expression closure
var squareAndCube = x => [x*x, x*x*x];
var [s,c] = squareAndCube(3);
// Expression closures
// doc: http://mzl.la/10TNpzc
// Warning: not part of the ES6 spec
var square = function(x) {
return x * x;
}
let square = function(x) x * x;
let square = x => x * x;
// Iterates over iterable objects
let arr = [ 3, 5, 7 ];
arr.foo = "hello";
for (let i of arr) { // OF
console.log(i); // logs "3", "5", "7"
}
for (let i in arr) { // IN
console.log(i); // logs "0", "1", "2", "foo"
}
let articleParagraphs = document.querySelectorAll("article > p");
for (let paragraph of articleParagraphs) {
paragraph.classList.add("read");
}
// let is the new var :)
// Declares a block scope local variable
var a = 1;
var b = 1;
if (true) {
var a = 0;
let b = 0;
}
console.log(a); // 0
console.log(b); // 1
// ---
let a = 5;
if (true) { let a = 6; alert(a) } // 6
alert(a); // 5
// key/value maps.
// let you associate an object to another one.
// Better than using an Object because you don't
// have to use a string.
let m = new Map();
m.set(obj_1, obj_a);
m.set(obj_2, obj_b);
m.get(obj_1); // returns obj_a;
Map.has(obj_2); // returns true
/* Rest arguments ********************************* */
function myLog(str, ...args) {
console.log(str + ":");
for (let arg of args) {
console.log(" " + arg);
}
}
myLog("foo", "foobar", "mopmop");
// output:
// foo:
// foobar
// mopmop
// Unordered collections of unique elements
// Better than using an array + indexOf as it ensures
// you the object is stored only once.
let trackedElement = new Set();
trackedElement.add(div1);
trackedElement.add(div2);
trackedElement.add(div1);
trackedElement.has(div1); // true
trackedElement.delete(div1);
trackedElement.has(div1); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment