To reduce state changes, you prevent two things from happening:
- reassignments
- mutations
-
You should always declare variables with const. When you declare variables with const, you'll see the const keyword. It is a good indicator that the variable is created in the current scope; it will never change the external state.
-
If you need a if/else statement to determine what value your variable should take, consider using a ternary operator instead of an if/else statement.
-
If you need three or more if statements, consider writing a function that uses an early return. This makes your code more declarative as a result.
You can prevent objects from mutating through two methods:
Object.assign
assignment
- Combine two objects with
Object.assign.
const car = {
type: 'car',
fueltype: 'gas',
wheels: 4
}
const teslaOptions = {
color: 'black',
fueltype: 'electric'
}
const createVehicle = (baseObj, objOptions) => Object.assign({}, baseObj, objOptions)
const newTesla = createVehicle(car, teslaOptions)
console.log(newTesla)
// => color: "black", fueltype: "electric", type: "car", wheels: 4- Combine two objects with
assignment.
const car = {
vehicleType: {
car: true
class: 'c'
},
fueltype: 'gas',
wheels: 4
}
const teslaOptions = {
color: 'black',
fueltype: 'electric',
package: {
trim: 'S',
line: '95'
}
}
const createVehicle = (baseObj, objOptions) => assignment({}, baseObj, objOptions)
const newTesla = createVehicle(car, teslaOptions)Array.slice - you tell JavaScript which parts of the array you want to copy out as your new array.
const newArray = array.slice(startIndex, endIndex)
// omit indexes to get the entire array
const copyArray = array.slice();Array.concat - combines 2 arrays to form a new one.