Create a gist now

Instantly share code, notes, and snippets.

@paulrouget /es6.js
Last active Oct 6, 2015

What would you like to do?
Some ECMAScript 6 element are available in Firefox
// To test this code in Firefox, I encourage you to use Firefox Aurora
// and to include your script this way:
// <script type="application/javascript;version=1.8">
// (necessary to make `let` work)
/* let ********************************************* */
// let is the new var :)
// Declares a block scope local variable
var a = 5;
if (1 == 1) { let a = 6; alert(a); } // 6
alert(a); // 5
/* Default Arguments ****************************** */
function myLog(str, prefix="> ", suffix="") {
console.log(prefix + str + suffix);
}
myLog("foobar!");
// output:
// > foobar!
/* For ... of ************************************** */
// 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");
}
/* 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
/* Map ******************************************** */
// Not iterable yet. Will be in a week. bug 725909.
// 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); // return obj_a;
/* Set ******************************************** */
// Not iterable yet. Will be in a week. bug 725909.
// 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

A detail: the if (1 == 1) in if (1 == 1) { let a = 6; alert(a); } // 6 at line 11 is not necessary. { let a = 6; alert(a); } works just fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment