Skip to content

Instantly share code, notes, and snippets.

@andyError
Last active June 27, 2019 15:24
Show Gist options
  • Save andyError/b1122c986431c48d77c10ce705a9608c to your computer and use it in GitHub Desktop.
Save andyError/b1122c986431c48d77c10ce705a9608c to your computer and use it in GitHub Desktop.
ES6 Crib sheet
- Template Literals
- Destructuring objects
- Destructuring arrays
- Object Literal
- For of loop
- Spread operator
- Rest operator
- Arrow Functions
- Default Params
- Array.includes()
- Let & const
- Export & import
- String.padStart(), String.padEnd()
- Classes
- Async/Await
- Sets in ES6
/* Template literals */
let word1 = 'Dylan';
let word2 = 'Israel';
const fullName = `${word1} ${word2}`;
console.log(fullName); // Dylan Israel
/* Destructuring objects */
const personalInformation = {
firstName: 'Dylan',
lastName: 'Israel',
city: 'Austin',
state: 'Texas',
zipCode: 73301
};
const {firstName, lastName} = personalInformation;
console.log(`${firstName} ${lastName}`); // Dylan Israel
const {firstName: fn, lastName: ln} = personalInformation;
console.log(`${fn} ${ln}`); // Dylan Israel
/* Destructuring arrays */
let [firstName, middleName, lastName] = ['Dylan', 'Coding God', 'Israel'];
console.log(firstName + middleName); // DylanCoding God
function addressMaker(city, state) {
const newAdress = {newCity: city, newState: state};
console.log(newAdress);
}
addressMaker('Austin', 'Texas');
/* Object literals */
function addressMaker(city, state) {
// const newAddress = {newCity: city, newState: state};
// You can do this instead…
const newAddress = {city, state};
console.log(newAdress);
}
addressMaker('Austin', 'Texas');
/* For of loop */
let incomes = [62000, 67000, 75000];
let total = 0;
for (const income of incomes) {
total += income;
}
console.log(total); // 204000
// Can be used with strings too, to loop over characters
/* Spread operator */
let example1 = [1,2,3,4,5,6];
let example2 = [...example1];
example2.push(true);
console.log(example2); // [1, 2, 3, 4, 5, 6, true]
/* Rest operator */
function add(...nums) {
console.log(nums);
}
add(4, 5, 7, 8, 12); // [4, 5, 7, 8, 12]
/* Arrow functions */
function add(...nums) {
let total = nums.reduce((x, y) => x + y);
console.log(total);
}
add(4, 5, 7, 8, 12);
/* Default params */
function add(numArray = []) { // This default empty array stops the function from breaking if nothing is passed in
let total = 0;
numArray.forEach((element) => {
total =+ element;
});
console.log(total);
}
add();
/* includes() */
let numArray = [1,2,3,4,5];
console.log(numArray.includes(0)) // false
console.log(numArray.includes(2)) // true
/* Let & Const */
// Variables declared with var get hoisted…
if (false) { var example = 5; }
console.log(example) // null - it recognises that the variable exists
// …variables declared with let and const don't - they have block scope.
if (false) { let example = 5; }
console.log(example) // ReferenceError: example is not defined (/index.js:7)
const example = 5;
example = 10;
console.log(example) // Error: SyntaxError: unknown: "example" is read-only (/index.js:1)
// Though if a const array or object is defined the contents CAN be changed
/* Import & export */
// In example.js
export const data = [1,2,3];
// In another file
import { data } from './example.js';
let updatedData = data;
updatedData.push(5)
console.log(updatedData); // [1, 2, 3, 5]
/* padStart() & padEnd() */
let example = 'Dylan';
console.log(example.padStart(10, 'a')); // aaaaaDylan
console.log(example.padEnd(10, 'a')); // Dylanaaaaa
let example = 'Dylan Israel';
console.log(example.padStart(10, 'a')); // Dylan Israel
console.log(example.padEnd(10, 'a')); // Dylan Israel
/* Classes */
export class Animal {
constructor(type, legs) {
this.type = type;
this.legs = legs;
}
makeNoise(sound = 'Loud Noise') {
console.log(sound);
}
get metaData() {
return `Type: ${this.type}, Legs: ${this.legs}`;
}
static return10() {
return 10;
}
}
class Dog extends Animal {
makeNoise(sound = "woof") {
console.log(sound);
}
}
// Instance of Animal class
let cat = new Animal('Cat', 4);
cat.legs = 3;
cat.makeNoise('Meow'); // Meow
console.log(cat.legs); // 3
console.log(cat.metaData); // Type: Cat, Legs: 4
// Instance of child class Dog
let dog = new Dog('Dog', 4);
dog.makeNoise(); // Woof
// Static function, no instance of class needed
console.log(Animal.return10()); // 10
/* Async & await */
const apiUrl = 'https://fcctop100.herokuapp.com/api/fccusers/top/alltime';
async function getTop100Campers() {
const response = await fetch(apiUrl);
const json = await response.json();
console.log(json[0]);
}
// function getTop100Campers() {
// fetch(apiUrl)
// .then((r) => r.json())
// .then((json) => {
// console.log(json[0])
// }).catch((error) =>{
// console.log('failed');
// });
// }
getTop100Campers(); //{username: "sjames1958gm", img: "https://avatars1.githubusercontent.com/u/4639625?v=4", alltime: 8826, recent: 104, lastUpdate: "2018-04-04T09:10:12.456Z"}
// …more
function resolveAfter3Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 3000);
});
}
// resolveAfter3Seconds().then((data) => {
// console.log(data);
// });
async function getAsyncData() {
const result = await resolveAfter3Seconds();
console.log(result);
}
getAsyncData();
/* Sets in ES6 */
const exampleSet = new Set([1,1,1,1,2,2,2,2]);
exampleSet.add(5);
exampleSet.add(5).add(17);
console.log(exampleSet.has(5)); // true
console.log(exampleSet.size); // 4
exampleSet.clear();
console.log(exampleSet.size); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment