Sitemap
Noel Pulido

Noel Pulido

Simple Coder

JavaScript Arrays

2 min readDec 4, 2022
Press enter or click to view image in full size
Photo by Jose Mueses from Pexels: https://www.pexels.com/photo/photo-of-five-cars-parked-1280560/

What is an array? Array is a single variable with multiple values in it. Here is an example of an array

names = ['Noel', 'Jhoana', 'Alexis', 'Rejinald']

As you can see on sample above, the variable names have 4 values in it.

Before we go farther, if we need an array in our code, we need to declare them first.

Array Declaration

Declare an empty array
let names = [ ];

Declare array with multiple values
let names = ['Noel', 'Jhoana', 'Alexis', 'Rejinald']

Accessing the values

Each element of an array has assigned number called index. We can use index to access the values. The index starts with zero and increment by one on the next value.

Syntax: arrayName[index]

Example:

let names = [’Noel’, 'Jhoana’, 'Alexis’, 'Rejinald’];
//the value 'Noel' has an index of 0 (zero).
//the value 'Jhoana' has an index of 1.
//the value 'Alexis" has an index of 2.
//the value 'Rejinald' has an index of 3.
console.log(names);
// output: ['Noel', 'Jhoana', 'Alexis', 'Rejinald'];
console.log(names[0]);
//output: Noel
console.log(names[2]);
//output: Alexis

Adding value(s) to array using push ()

The push method adds new value(s) at the end of the array.

Get Noel Pulido’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax: arrayName.push(valueToAdd)

Example:

let names = ['Noel', 'Jhoana', 'Alexis', 'Rejinald']; 
names.push('Che');
console.log(names);
//output
// ['Noel', 'Jhoana', 'Alexis', 'Rejinald', 'Che'];

You can also add multiple values and use comma as a separator.
Example:

let names = ['Noel', 'Jhoana', 'Alexis', 'Rejinald'];
names.push('Che', 'Fe');
console.log(names);
//output
// ['Noel', 'Jhoana', 'Alexis', 'Rejinald', 'Che', 'Fe'];

Deleting value in array using pop () method

This method removes the last value in the array
Syntax: arrayName.pop()

Example:

let names = ['Noel', 'Jhoana', 'Alexis', 'Rejinald'];
names.pop();
console.log(names);
//output
//['Noel', 'Jhoana', 'Alexis'];

The filter() method

The filter method creates a new array on which every value passes the condition that was provided by a function.

Syntax: arrayName.filter(function)

Example:

let numbers= [1, 3, 5, 7, 9]; 
let filteredArray = numbers.filter(getUnderSix);
function getUnderSix(num){
return num < 6;
}
console.log(filteredArray);
//output
// [1, 3, 5]

My two cents

Array helps us not only holding multiple values, but also on holding a group within a category. We can have an array of first name, array of fruit names so on and so forth. It also makes our code lesser, neat and easy to understand. Methods mentions above are only few that we could use to an array. See https://www.w3schools.com/js/js_arrays.asp for more about JavaScript arrays.

--

--