ES6
JavaScript ES6: Cheetsheet
// => Hello world!
console.log('Hello world!');
// => Hello QuickRef.ME
console.warn('hello %s', 'QuickRef.ME');
// Prints error message to stderr
console.error(new Error('Oops!'));
let age = 7;
// String concatenation
'Tommy is ' + age + ' years old.';
// String interpolation
`Tommy is ${age} years old.`;
const numberOfColumns = 4;
// TypeError: Assignment to constant...
numberOfColumns = 8;
var x=1;
// => true
result = (x == 1) ? true : false;
null ?? 'I win'; // 'I win'
undefined ?? 'Me too'; // 'Me too'
false ?? 'I lose' // false
0 ?? 'I lose again' // 0
'' ?? 'Damn it' // ''
0 == false // true
0 === false // false, different type
1 == "1" // true, automatic type conversion
1 === "1" // false, different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
Arrow function available starting ES2015
const sum = (param1, param2) => {
return param1 + param2;
};
console.log(sum(2,5)); // => 7
const printHello = () => {
console.log('hello');
};
printHello(); // => hello
const checkWeight = weight => {
console.log(`Weight : ${weight}`);
};
checkWeight(25); // => Weight : 25
const multiply = (a, b) => a * b;
// => 60
console.log(multiply(2, 30));
function myFunction() {
var pizzaName = "Margarita";
// Code here can use pizzaName
}
// Code here can't use pizzaName
const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
console.log(statusMessage);
// Variable declared globally
const color = 'blue';
function printColor() {
console.log(color);
}
printColor(); // => blue
var
is scoped to the nearest function blocklet
is scoped to the nearest enclosing blockfor (let i = 0; i < 3; i++) {
// This is the Max Scope for 'let'
// i accessible ✔️
}
// i not accessible ❌
for (var i = 0; i < 3; i++) {
// i accessible ✔️
}
// i accessible ✔️
The variable has its own copy using let
, and the variable has shared copy using var
.
// Prints 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
setTimeout(_ => console.log(i), 10);
}
// Prints 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
setTimeout(_ => console.log(j), 10);
}
Function \ Result | add | remove | start | end |
---|---|---|---|---|
push | ✔ | ✔ | ||
pop | ✔ | ✔ | ||
unshift | ✔ | ✔ | ||
shift | ✔ | ✔ |
// Adding a single element:
const cart = ['apple', 'orange'];
cart.push('pear');
// Adding multiple elements:
const numbers = [1, 2];
numbers.push(3, 4, 5);
const fruits = ["apple", "orange", "banana"];
const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]
let cats = ['Bob', 'Willy', 'Mini'];
cats.shift(); // ['Willy', 'Mini']
let cats = ['Bob'];
// => ['Willy', 'Bob']
cats.unshift('Willy');
// => ['Puff', 'George', 'Willy', 'Bob']
cats.unshift('Puff', 'George');
const numbers = [3, 2, 1]
const newFirstNumber = 4
// => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers)
// => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber)
const fruits = ["apple", "orange", "banana"];
for (let index in fruits) {
console.log(index);
}
// => 0
// => 1
// => 2
const fruits = ["apple", "orange", "banana"];
for (let fruit of fruits) {
console.log(fruit);
}
// => apple
// => orange
// => banana
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, curVal) => {
return accumulator + curVal;
});
console.log(sum); // 10
const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"];
const announcements = members.map((member) => {
return member + " joined the contest.";
});
console.log(announcements);
const numbers = [28, 77, 45, 99, 27];
numbers.forEach(number => {
console.log(number);
});
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {
return n > 5;
});
// Example of invalid key names
const trainSchedule = {
// Invalid because of the space between words.
platform num: 10,
// Expressions cannot be keys.
40 - 10 + 2: 30,
// A + sign is invalid unless it is enclosed in quotations.
+compartment: 'C'
}
const person = {
name: 'Tom',
age: '22',
};
const {name, age} = person;
console.log(name); // 'Tom'
console.log(age); // '22'
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
goal: "learning JavaScript"
};
delete person.hobby; // or delete person[hobby];
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
const activity = 'Surfing';
const beach = { activity };
console.log(beach); // { activity: 'Surfing' }
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name
}
};
console.log(cat.whatName()); // => Pipey
// A factory function that accepts 'name',
// 'age', and 'breed' parameters to return
// a customized dog object.
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
}
};
};
const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter: () => {
console.log('The engine sputters...');
},
};
engine.start('noisily');
engine.sputter();
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};
// Reference invokes the getter
console.log(myCat.name);
// Assignment invokes the setter
myCat.name = 'Yankee';
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
console.log('This is ' + this._name + ' !');
}
// A static method
static bark() {
console.log('Woof!');
}
}
const myDog = new Dog('Buster');
myDog.introduce();
// Calling the static method
Dog.bark();
// Parent class
class Media {
constructor(info) {
this.publishDate = info.publishDate;
this.name = info.name;
}
}
// Child class
class Song extends Media {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}
const mySong = new Song({
artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975
});
// myMath.js
// Default export
export default function add(x,y){
return x + y
}
// Normal export
export function subtract(x,y){
return x - y
}
// Multiple exports
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
export {
multiply,
duplicate
}
// main.js
import add, { subtract, multiply, duplicate } from './myMath.js';
console.log(add(6, 2)); // 8
console.log(subtract(6, 2)) // 4
console.log(multiply(6, 2)); // 12
console.log(duplicate(5)) // 10
// index.html
<script type="module" src="main.js"></script>
// myMath.js
function add(x,y){
return x + y
}
function subtract(x,y){
return x - y
}
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
// Multiple exports in node.js
module.exports = {
add,
subtract,
multiply,
duplicate
}
// main.js
const myMath = require('./myMath.js')
console.log(myMath.add(6, 2)); // 8
console.log(myMath.subtract(6, 2)) // 4
console.log(myMath.multiply(6, 2)); // 12
console.log(myMath.duplicate(5)) // 10
const promise = new Promise((resolve, reject) => {
const res = true;
// An asynchronous operation.
if (res) {
resolve('Resolved!');
}
else {
reject(Error('Error'));
}
});
promise.then(
(res) => console.log(res),
(err) => console.error(err)
);
const executorFn = (resolve, reject) => {
resolve('Resolved!');
};
const promise = new Promise(executorFn);
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result');
}, 200);
});
promise.then((res) => {
console.log(res);
}, (err) => {
console.error(err);
});
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('Promise Rejected Unconditionally.'));
}, 1000);
});
promise.then((res) => {
console.log(value);
});
promise.catch((err) => {
console.error(err);
});
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 300);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});
Promise.all([promise1, promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('*');
}, 1000);
});
const twoStars = (star) => {
return (star + star);
};
const oneDot = (star) => {
return (star + '.');
};
const print = (val) => {
console.log(val);
};
// Chaining them all together
promise.then(twoStars).then(oneDot).then(print);
const executorFn = (resolve, reject) => {
console.log('The executor function of the promise!');
};
const promise = new Promise(executorFn);
const promise = new Promise(resolve => setTimeout(() => resolve('dAlan'), 100));
promise.then(res => {
return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')
}).then((res) => {
console.log(res)
}, (err) => {
console.error(err)
});
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
const msg = async function() { //Async Function Expression
const msg = await helloWorld();
console.log('Message:', msg);
}
const msg1 = async () => { //Async Arrow Function
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
msg1(); // Message: Hello World! <-- after 2 seconds
let pro1 = Promise.resolve(5);
let pro2 = 44;
let pro3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([pro1, pro2, pro3]).then(function(values) {
console.log(values);
});
// expected => Array [5, 44, "foo"]
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
let json = '{ "age": 30 }'; // incomplete data
try {
let user = JSON.parse(json); // <-- no errors
console.log( user.name ); // no name!
} catch (e) {
console.error( "Invalid JSON data!" );
}
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message)
})
fetch('url-that-returns-JSON')
.then(response => response.json())
.then(jsonResponse => {
console.log(jsonResponse);
});
fetch('url')
.then(
response => {
console.log(response);
},
rejection => {
console.error(rejection.message);
}
);
fetch('https://api-xxx.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: "200"})
}).then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
console.log(jsonResponse);
})
const getSuggestions = async () => {
const wordQuery = inputField.value;
const endpoint = `${url}${queryParams}${wordQuery}`;
try{
const response = await fetch(endpoint, {cache: 'no-cache'});
if(response.ok){
const jsonResponse = await response.json()
}
}
catch(error){
console.log(error)
}
}
JavaScript ES6: Cheetsheet
JavaScript ES6 Cheetsheet: AKA (also known as)
JavaScript ES6 Cheetsheet: Destructuring
JavaScript Number: Cheetsheet
JavaScript Http Code: Cheetsheet