Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

JS Arrays


JavaScript Arrays

JavaScript arrays are data structures that allow you to store and manipulate collections of data. They are similar to lists or arrays in other programming languages.

To create an array in JavaScript, you can use square brackets and separate the items with commas.

The Array syntax is as per below:

const array_name = [item1, item2, ...];

Example:

const people = ["John", "Gemma", "Tom"];

In this example, the array people contains three string elements: "John", "Gemma", "Tom".

Accessing Arrays

1. Selecting one item from the Array:

               
                
<p id="display"></p>

<script>
const people = ["John", "Gemma", "Tom"];
document.getElementById("display").innerHTML = people[1];
</script>
                
                
              

2. Selecting and displaying all elements

     
      
<p id="displayall"></p>

<script>
const friends = ["Albert", "Gina", "Mike"];
document.getElementById("displayall").innerHTML = people;
</script>
                
                
              

Adding and removing items from the Array

With Arrays there are lots of things you can do, like adding or removing items from the array.

a. You can add new elements to an array using the push() method:

friends.push("Amanda");
console.log(friends); // ["Albert", "Gina", "Mike", "Amanda"]

b. You can remove elements from an array using the pop() method:

friends.pop();
console.log(friends); // ["Albert", "Gina", "Mike"]