The let keyword declares block-scoped variables in contrast to the var keyword which declares function-scoped or global variables.
The const keyword declares block-scoped constants.
let { bar } = foo // where foo = { bar:10, baz:12 };
const { bar } = foo // where foo = { bar:10, baz:12 };
// 1. Typical arrow function.
(a, b) => {
return a + b
}
// 2. One-liner without braces, the return is implied.
(a, b) => a + b
// 3. With one argument the parentheses can be removed.
a => a + 1
// 4. Return an object.
const mapStateToProps = state => ({});
Returns a new array populated with the results of the provided function for each iteration:
const newItems = items.map((x) => x + 1)
Returns a new array populated with filtered results which return true in the provided function.
const filteredItems = items.filter((item) => item.length > 3)
Returns a copy of a portion of an array.
const newItems = items.slice(2, 4)
// Use the spread operator.
const newArray = [...oldArray]
Creates an array from array-like objects.
Array.from([1, 2, 3], (x) => x + x)
Returns the value of the first element that matches the conditions in the provided callback function.
const foundItem = items.find((item) => item.id === 3)
Loops through iterable objects including arrays.
const array = [1, 2, 3]
for (const item of array) {
console.log(item)
}
The break and return statements do not stop the loop.
array.forEach(function (item) {
console.log(item)
}
Loop through object properties. Avoid using for...in with arrays.
const object = { a: 1, b: 2, c: 3 }
for (const property in object) {
console.log(property)
}
class Car extends Vehicle {
constructor(name) {
super() // Call the parent constructor.
this.name = name
}
changeName(name) {
this.name = name
}
}
const car1 = new Car("BMW")
// Named export.
export class Car extends Vehicle {}
// Named import.
import { Car } from "./car"
// Default export.
export default class Car extends Vehicle {}
// Default import.
import Car from "./car"
let promise = new Promise(function(resolve, reject) {
// async logic ...
if (/* everything is OK */) {
resolve("Success!");
}
else {
reject("Something went wrong!");
}
});
promise.then((message) => {
// do something.
}).catch((message) => {
// do something with the error.
})
Run promises in parallel.
Promise.all([promise1, promise2, promise2]).then((messages) => {
// messages is an array with the successful results.
// It will resolve only when all the promises have resolved.
})
async function doStuff() {
try {
// Waits the resolved promise value.
let result = await asyncFunction()
} catch (error) {
// Get the rejected promise value.
}
}