JavaScript Arrays

An array stores many values in one variable, in order. Each item has an index that starts from 0.

const fruits = ["apple", "banana", "mango"];

console.log(fruits[0]);
console.log(fruits[2]);
console.log(fruits.length);
console.log(fruits.at(-1));
Output of the above program is

apple
mango
3
mango


Add and remove items

MethodWhat it does
push(x)Adds at the end
pop()Removes the last item
unshift(x)Adds at the start
shift()Removes the first item
splice(start, count, ...items)Removes or inserts items at a position
slice(start, end)Copies a part, does not change the original
const list = ["a", "b", "c"];

list.push("d");
console.log(list);
list.pop();
list.unshift("z");
console.log(list);
list.splice(1, 1);        // remove 1 item at index 1
console.log(list);
console.log(list.slice(0, 2));
Output of the above program is

[ "a", "b", "c", "d" ]
[ "z", "a", "b", "c" ]
[ "z", "b", "c" ]
[ "z", "b" ]


Search and join

const nums = [10, 20, 30];
console.log(nums.includes(20));
console.log(nums.indexOf(30));
console.log(nums.join(" - "));
console.log([1, 2].concat([3, 4]));
console.log([...nums, 40]);
Output of the above program is

true
2
10 – 20 – 30
[ 1, 2, 3, 4 ]
[ 10, 20, 30, 40 ]


Loop over an array

const colors = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color);
}

colors.forEach((color, index) => {
  console.log(index + ": " + color);
});
Output of the above program is

red
green
blue
0: red
1: green
2: blue

Note: An array is an object, so typeof [] is "object". Use Array.isArray() to check. Even a const array can change its items, only the variable cannot be reassigned.

Summary

  • Arrays hold ordered values and start at index 0.
  • push/pop work at the end, unshift/shift at the start, splice anywhere.
  • Loop with for...of or forEach.
  • Next: Array Methods.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.