5 Critical Javascript Methods You Need To Know For React

While working with React, Vue, Angular, and other frameworks, I find myself writing lots of normal Javascript while working with arrays. Methods like slice(), shift(), find(), filter(), and map() are all over my React app code, but I’ve never prioritized digging into them.

I went way too long copy/pasting someone else’s code from StackOverflow, and not really understanding these methods. That was a mistake!

These are the 5 most common methods I find myself using over and over while working with React and other frameworks. These are worth memorizing.

map()

array.map(function(currentValue, index, arr), thisValue)

The map method is commonly used in React to render an array. I use it a lot to display an array of objects, such as posts or products.

Simple Example

const arr = [1,2,3,4];
const newArr = arr.map( val => val + 1 );
console.log(newArr) // 2,3,4,5

The map method takes an array, along with a function to manipulate each item. You can also get the index and original array in your callback function.

const arr = [1,2,3,4];
const newArr = arr.map( (val, index, arr) => val + index );
console.log(newArr) // 1,3,5,7

Map does not change the original array.

React Usage

In React, you commonly see it used to display an array of objects.

{ products && products.map( ( products, index ) => (
  <div key={ product.id }>{ product.name }</div>
)}

To memorize this method, I just think of spreading out all my objects on a physical map.

findIndex()

array.findIndex(function(currentValue, index, arr), thisValue)

This method is great for figuring out where an item is inside your array. This is commonly used to edit an object inside an array, such as updating a product cart quantity.

Simple Example

const arr = [1,2,3,4,5];
const itemIndex = arr.findIndex( item => item > 3 );
console.log( arr[itemIndex] ); // 4

The findIndex method only returns the first match. Tip: if you want all items that are greater than 3 in the example above, you would use filter().

How is this different than find()? The find method returns the item instead of the item’s index.

React Example

In this example, we want to update the quantity of the Watch in our cart. We will build on this example below using splice().

const cart = [{id: 1, name: 'Hat', quantity: 1}, {id: 2, name: 'Watch', quantity: 1}];
let itemIndex = cart.findIndex( item => item.name === "Watch" );
console.log( cart[itemIndex] ) // {id: 2, name: 'Watch', quantity: 1}

splice()

array.splice(index, howmany, item1, ....., itemX)

Splice allows you to add elements to an array, and remove elements at the same time. That’s kind of confusing, so I think of it as replacing an item.

Simple Example

const arr = [1,2,3,4,5,6];
// replace 1 item at index 2 with the new value
arr.splice(2,1,"tie my shoe");
console.log(arr) // 1,2,"tie my shoe",4,5,6

Splice changes the original array, so you wouldn’t create a new variable like we did with map().

React Example

I use splice() to edit an object inside an array. For example, updating a cart item quantity.

import { useState } from 'react';

const Cart = () => {
  
  const products = [{id: 1, name: 'Hat', quantity: 1}, {id: 2, name: 'Watch', quantity: 1}];

  // setup some simple products in state so we can change the quantity
  const [ demoCart, setDemoCart ] = useState( products );

  const addWatch = () => {
    // increase quantity of Watch
    // first we need to figure out where the watch is in our array
    let itemIndex = demoCart.findIndex( item => item.name === "Watch" );

    // once we have the array index, we can grab the object, increase the quantity
    let newItem = demoCart[itemIndex];
    newItem.quantity++;

    // then we use splice to swap out the old item with the new item
    demoCart.splice(itemIndex, 1, newItem);
    setDemoCart( demoCart );
  }
  
  return( 
    // cart markup here
  )
}

Why would we use splice here instead of directly updating the cart item? Because state is immutable in React, meaning you can’t directly edit the cart item. Instead we need to create a new instance using splice.

push()

array.push(item1, item2, ..., itemX)

The push method adds an item to the end of an array. You will use this frequently to add an item to a cart, add a post to a list of favorites, etc.

Simple Example

const arr = [{id:1,name:"Post One"},{id:2,name:"Post Two"}]
arr.push({id:3,name:"Post Three"})
console.log(arr) // [{id:1,name:"Post One"},{id:2,name:"Post Two"},{id:3,name:"Post Three"}]

The push method modifies the original array and returns the new length (not the new array).

If you wanted to add an item to the beginning of the array, you’d use unshift().

React Example

The push method is often used to add an item to a shopping cart.

function addToCart( product ) => {
  const products = state.products;
  products.push( product );
  setState( products );
}

Subscribe

Get more great content like this, enter your email below.

Share

Loading comments...

Leave a comment

Your email address will not be published. Required fields are marked *