Background
immutable(unchangeable) means that something cannot be changed. In the programming language Elixir and Erlang, immutable variables are used.mutableis the opposite, meaning that something can be changed.
Examples
- Overwriting objects
let person = {
firstName: "Bob",
lastName: "Loblaw",
address: {
street: "123 Fake St",
city: "Emberton",
state: "NJ"
}
}
function giveAwesomePowers(person) {
person.specialPower = "invisibility";
return person;
}
// Initially, Bob has no powers :(
console.log(person);
// Then we call our function...
let samePerson = giveAwesomePowers(person);
// Now Bob has powers!
console.log(person);
console.log(samePerson);
- A new object is created, so the original object is not overwritten
function giveAwesomePowers(person) { let newPerson = Object.assign({}, person, { specialPower: 'invisibility' }) return newPerson; }
- Alternatively
function giveAwesomePowers(person) { let newPerson = { ...person, specialPower: 'invisibility' } return newPerson; }
Tic Tac Toe
- “wrong”
const [gameBoard, setGameBoard] = useState(initialGameBoard);
function handleSelectSquare(rowIndex, colIndex, playerSymbol) {
setGameBoard((prevGameBoard) => {
prevGameBoard[rowIndex][colIndex] = 'X';
return prevGameBoard;
});
}
- “correct”
function handleSelectSquare(rowIndex, colIndex) {
setGameBoard((prevGameBoard) => {
const updatedBoard = [...prevGameBoard.map(innerArray =>[...innerArray])];
updatedBoard[rowIndex][colIndex] = 'X';
return updatedBoard;
});
}
Notes
- A pure function must always return the same value when given the same inputs.
- A pure function should not have side effects.
Caution with the Following Array Methods
push (add an item to the end)
pop (remove an item from the end)
shift (remove an item from the beginning)
unshift (add an item to the beginning)
sort
reverse
splice
Sorting
let sortedArray = [...originalArray].sort(compareFunction);