Skip to content

Instantly share code, notes, and snippets.

@joe-lloyd
Last active February 19, 2024 16:29
Show Gist options
  • Save joe-lloyd/4d36def9073bf7dfbbd8675a5381b495 to your computer and use it in GitHub Desktop.
Save joe-lloyd/4d36def9073bf7dfbbd8675a5381b495 to your computer and use it in GitHub Desktop.
Mutation in JavaScript with slice and splice
/**
* Mutation in JavaScript
* Core concepts and examples of mutation in JavaScript
*/
const coreConcepts = () => {
// Creating a new object
const myObj = { key: "some value" };
// Assigning myObj to newObj by reference
const newObj = myObj;
// Changing newObj also changes myObj because of the reference
newObj.key = "some other value";
// Logging myObj shows the mutated value
console.log(myObj); // Outputs: { key: "some other value" }
}
/**
* Using splice (mutating array)
*/
const usingSplice = () => {
// Define a new object with an array inside to replicate the props object in react
const props = {
someArray: [2, 5, 6, 8, 10],
};
let yourArray = props.someArray;
let halfwayThrough = Math.floor(yourArray.length / 2);
// Using splice to remove the first half from yourArray and store it in arrayFirstHalf
let arrayFirstHalf = yourArray.splice(0, halfwayThrough);
console.log(arrayFirstHalf); // Outputs: [2, 5, 6]
console.log(yourArray); // Outputs: [8, 10]
// This means that yourArray is actually the arraySecondHalf now
};
/**
* // Using slice (no mutation)
*/
const usingSlice = () => {
// Define a new object with an array inside to replicate the props object in react
const props = {
someArray: [2, 5, 6, 8, 10],
};
let yourArray = props.someArray;
let halfwayThrough = Math.floor(yourArray.length / 2);
let arrayFirstHalf = yourArray.slice(0, halfwayThrough);
let arraySecondHalf = yourArray.slice(halfwayThrough);
console.log(arrayFirstHalf); // Outputs: [2, 5, 6]
console.log(arraySecondHalf); // Outputs: [8, 10]
console.log(yourArray); // Outputs: [2, 5, 6, 8, 10]
// This means that yourArray is still the same as the original array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment