JS - Best Practices (Side effects)

Accidentally modifying global variable :

Bad :

// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
let name = 'Ryan McDermott';

function splitIntoFirstAndLastName() {
    name = name.split(' ');
}

splitIntoFirstAndLastName();
console.log(name); // ['Ryan', 'McDermott'];

Correct :

function splitIntoFirstAndLastName(name) {
     return name.split(' ');
}

const name = 'Ryan McDermott';
const newName = splitIntoFirstAndLastName(name);

console.log(name); // 'Ryan McDermott';
console.log(newName); // ['Ryan', 'McDermott'];

 

In JavaScript, primitives are passed by value and objects/arrays are passed by reference :

Bad :

//any other function that uses that cart array will be affected by this addition.
const addItemToCart = (cart, item) => {
      cart.push({ item, date: Date.now() });
};

Correct :

//clone the cart, edit it, and return the clone
const addItemToCart = (cart, item) => {
     return [...cart, { item, date: Date.now() }];
};

 
 

js best practices