An array stores a list of values in one variable.
const fruits = ['Apple', 'Mango', 'Banana'];
Read and change
fruits[0]→'Apple'(index starts at 0)fruits.length→3fruits[1] = 'Grapes';changes an item- Last item:
fruits[fruits.length - 1]orfruits.at(-1)
Add and remove
| Method | Does |
|---|---|
push(x) |
add to the end |
pop() |
remove from the end |
unshift(x) |
add to the start |
shift() |
remove from the start |
splice(i, n) |
remove n items at index i |
Check
Array.isArray(value) tells you if something is an array (typeof says "object").
Example
Example — Shopping list
HTML
<input id="item" placeholder="Add item">
<button onclick="addItem()">Add</button>
<button onclick="removeLast()">Remove last</button>
<ol id="list"></ol>
<script>
const items = ['Milk', 'Bread'];
function render() {
document.getElementById('list').innerHTML =
items.map(i => `<li>${i}</li>`).join('');
}
function addItem() {
const input = document.getElementById('item');
if (input.value.trim()) items.push(input.value.trim());
input.value = '';
render();
}
function removeLast() {
items.pop();
render();
}
render();
</script>