Helpful ES6 Syntax to Know for React and Beyond ⚛️
The Following are Used heavily in Mod 4 for React (and are important to know if you're writing modern JavaScript):
// Object Destructuring
const spaceship = {
pilot: 'Elon Musk',
guidance: 'John Cena',
chef: 'Gordon Ramsay'
}
const { pilot, guidance } = spaceship
console.log(pilot)
console.log(guidance)
// Class definition
class Person {
constructor(props){
this.name = props.name
this.favColor = props.favColor
}
}
// VS
class Person {
constructor({name, favColor}){
this.name = name
this.favColor = favColor
}
}
Key-Value Assignment Shortcuts
const pizza = 'pepperoni'
const restaurant = 'dominos'
const pizzaObj = {
pizza: pizza,
restaurant: restaurant
}
// VS
const pizzaObj2 = { pizza, restaurant }
const obj1 = {
first_name: 'John',
last_name: 'Doe'
}
// Creating an exact copy of the object
const obj2 = {
...obj1,
favColor: 'Matt Black'
}
// OR
const obj3 = Object.assign({ favColor: 'matt black'},obj1)
// VS
const obj4 = obj1
obj4.favColor = 'Red'
console.log(obj4)
Array.prototype.myFilter = function(callback){
const filtered = []
for(let i = 0; i < this.length; i++) {
const currentElement = this[i]
if(callback(currentElement)){
filtered.push(currentElement)
}
}
return filtered
}
['Pizza','Taco','Sandwich','Wrap'].myFilter((snack) => snack === 'Pizza')
All forms of the arrow function
const implicitReturn = () => 'hi'
const explicitReturn = () => {
return 'hi'
}
Function binding vs arrow function
const dog = {
name: 'Scooby',
favSnack: ['Cheese', 'Peanut Butter', 'Carrots'],
sayName: function(){
return this.name
},
barkName: () => {
return this.name + 'BARK!!'
},
sayFavFoods: function(){
this.favSnack.forEach(snack => {
console.log(`${this.name} likes ${snack}`)
})
},
sayFavFoodsNoArrow: function(){
this.favSnack.forEach(function(snack){
console.log(`${this.name} likes ${snack}`)
})
}
}
dog.sayName() // => ???
dog.barkName() // => ???
dog.sayFavFoods() // => ???
dog.sayFavFoodsNoArrow() // => ???
Class instance properties and class syntax in general
class Dog{
constructor(name, age){
this.name = name
this.age = age
}
woofWoof(){
return `${this.name} says woof woof!`
}
}
Passing function around as callback and Iterators (map, reduce, forEach, filter, find etc..)
const powerfulPeople = ['Harry','Voldemort','Dumbledore','Grindelwald']
powerfulPeople.map((name) => name.toLowerCase())
const dynamicSetKeys = (obj, key, val) => {
obj[key] = val
return obj
}