To learn JavaScript, we must learn the basics.
In this article, we’ll look at the most basic parts of the JavaScript language.
Adding and Removing elements
We can add and remove array elements easily with JavaScript.
To add elements, we just assign a value to the array index we want.
For example, we can write:
let animals = [];
animals[0] = "dog";
animals[1] = "cat";
animals[2] = "mouse";
We created the animals
array by creating a variable and assigning it to an empty array.
Then we assign values to the given index of animals
.
We can do this for any index and the indexes don’t have to be consecutive or in order.
To remove the last item from the array, we call the pop
method:
animals.pop()
An alternative to add elements to an array is to use the push
method:
animals.push("fish", "bird");
push
adds elements to the end of the array.
To remove the first element of an array, we can shift
:
animals.shift();
To add one more elements to the beginning of an array, we call unshift
:
animals.shift("fish", "bird");
The splice
method insert one or more elements anywhere in the array:
pets.splice(2, 2, "pig", "duck", "emu");
The first argument is the starting index to insert.
The 2nd is number of items to remove.
The subsequent arguments are the items we want to insert in place of the removed items.
The slice
method lets us copy one or more consecutive elements in any position and put them in a new array.
For example, we can write:
let pets = animals.slice(2, 4);
to copy the items from index 2 to 3 from animals
and return that array.
The first argument is the starting index copy. The 2nd is 1 after the ending index to copy.
The 2nd index itself isn’t included in the range.
for loops
Loops are provided by JavaScript so we can run code repeatedly.
To do this, we can use the for
loop:
for (let i = 0; i <= 10; i++) {
if (city === cleanestCities[i]) {
console.log("It's one of the cleanest cities");
}
}
A for
loop is composed of the heading, which has the starting index, the condition to continue running the loop, and a statement to update the index.
In the loop body, we can do what we want.
In the example above, we check it city
is equal to cleanestCities[i]
.
And if it’s true
, we console log a message.
The loop index is used for accessing the array item and also to move the loop towards the ending condition, which is i <= 10
.
If i
is bigger than 10, then the loop stops.
We can also set flags in for
loops so that we can record some information/
For example, we can write:
let matchFound = false;
for (let i = 0; i <= 10; i++) {
if (city === cleanestCities[i]) {
matchFound = true;
console.log("It's one of the cleanest cities");
}
}
We set matchFound
to true
once we found a value from cleanesCities
that’s equal to city
.
Conclusion
We can add and remove elements with JavaScript array methods.
Also, we can loop through array items with a for
loop.