We do not need to define these?

In the Arrays in state section of React, I am quite confused about the definition of the keys, the section link is as below:
https://www.codecademy.com/courses/react-101/lessons/the-state-hook/exercises/arrays-in-state
and the code is as followings:

import React, { useState } from "react";
import ItemList from "./ItemList";
import { produce, pantryItems } from "./storeItems";

export default function GroceryCart() {
  const [cart, setCart] = useState([]);

  const addItem = (item) => {
    setCart((prev) => {
      return [item, ...prev];
    });
  };

  const removeItem = (targetIndex) => {
    setCart((prev) => {
      return prev.filter((item, index) => index !== targetIndex);
    });
  };

  return (
    <div>
      <h1>Grocery Cart</h1>
      <ul>
        {cart.map((item, index) => (
          <li onClick={() => removeItem(index)} key={index}>
            {item}
          </li>
        ))}
      </ul>
      <h2>Produce</h2>
      <ItemList items={produce} onItemClick={addItem} />
      <h2>Pantry Items</h2>
      <ItemList items={pantryItems} onItemClick={addItem} />
    </div>
  );
}

I am quite confused that we do not need to define that is ‘index’ or ‘target index’ or ‘item’ or ‘prev’? right?
we can use them directly?
so confused

1 Like

all the variable you name here, are parameters.

When we declare a function (or method, but example is with functions):

const example = (param) => {
    console.log(param);
} 

we can define parameter. Then we call the function:

example('hello world');

we provide argument(s) for the function. Given functions aren’t executed until called, parameters essentially act as placeholders

Understanding JavaScript, parameters and arguments, function definition and calls is vital. ReactJS adds a lot of abstraction/layers, you need to learn to see “through” these layers

2 Likes