JavaScript Arrays

What is an array?

Let's say, you have 3 users and you want to store their names:

const user1 = 'A';
const user2 = 'B';
const user3 = 'C';

What if you have 100? It will be 100 lines of codes.

Instead, we can store in an array like this:

const users = ['A', 'B', 'C', ...];

Creating an array

To create an array, we use the square bracket [].

Array can store any type of values.

// Array of strings
const names = ['A', 'B', 'C'];

// Array of numbers
const heights = [150, 160, 170];

// Array of objects
const users = [
    { id: 1, name: 'A' },
    { id: 2, name: 'B' },

And more... we will talk about Object in future sections.

Accessing an element

Element means the individual value in the array.

const names = ['A', 'B', 'C'];

A, B, and C are all called element in the names array.

We access the element by their position in that array. Note that in JavaScript and most of the programming languages, array starts with index 0.

const names = ['A', 'B', 'C'];

console.log(names[0]); // output: A
console.log(names[1]); // output: B
console.log(names[2]); // output: C

Changing an element

const names = ['A', 'B', 'C'];

names[0] = 'D';

console.log(names); // output: ['D', 'B', 'C']

Array methods

In JavaScript, there are tons of array methods. Here are some common ones, you can explore more here:

  1. W3 School
  2. MDN

Array.length - Get array's length

const nums = [1, 2, 3];

console.log(nums.length); // output: 3

Array.push - Add new element into array

const nums = [1, 2, 3];


console.log(nums); // output: [1, 2, 3, 4]

Did you find this article valuable?

Support Yap Yee Qiang by becoming a sponsor. Any amount is appreciated!