When working with JavaScript and React, there are a few core concepts that you’ll use again and again: arrays, the spread operator (...), the map() function, and React's useState hook. In this blog, we’ll break each one down with simple examples so you can understand how and when to use them effectively.
Arrays in JavaScript
An array is a list-like object used to store multiple values in a single variable.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Output: apple
Arrays can hold any data type — strings, numbers, objects, or even other arrays.
The Spread Operator (...)
The spread operator allows you to quickly copy or merge arrays and objects.
Copying an array:
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]
Adding elements:
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5];
console.log(moreNumbers); // [1, 2, 3, 4, 5]
Merging arrays:
const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4]
Using map() to Transform Arrays
The map() method lets you apply a function to every element in an array and returns a new array.
Example: Multiply each number by 2
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
In React, map() is commonly used to render lists of components:
const items = ['pen', 'notebook', 'eraser'];
return (
<ul>
{items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
);
useState in React
React's useState hook lets you add state to functional components.
Basic usage:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Updating an array with useState and the spread operator:
function TodoList() {
const [todos, setTodos] = useState(['Buy milk']);
const addTodo = () => {
setTodos([...todos, 'Walk the dog']);
};
return (
<>
<ul>
{todos.map((todo, index) => <li key={index}>{todo}</li>)}
</ul>
<button onClick={addTodo}>Add Todo</button>
</>
);
}
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.