This is an article with the notes that I summarized after learning「Introduction To JavaScript」in Codecademy.
Arrays
Arrays are JavaScript's way of making lists. These lists can store any data types including strings, numbers, and booleans. Each item in the list also has a numbered position. The following is an example that shows how an array looks like.
// My Favorite books:
// 1. Walden
// 2. Gitanjali
// 3. Stray Birds
let myFavoriteBooks = ['Walde', 'Gitanjali', 'Stray Birds'];
console.log(myFavoriteBooks);
// ['Walde', 'Gitanjali', 'Stray Birds']
Access an item in an array
// array positions start from 0, not 1
let seasons = ['Spring', 'Summer', 'Autumn', 'Winter'];
console.log(seasons[0]); // Spring
console.log(seasons[2]); // Autumn
// list can also be changed using position numbers
season[0] = 'Winter';
console.log(season[0]); // Winter
Different methods of array
There are many methods that can be used to change or to access an array, the following list includes the methods that developers frequently use.
.push(item)
ー adds the item in the end of an array
.pop()
ー removes the last item from an array
.join()
ー joins all items in array into a string
.slice()
ー extracts a section of an array and returns a new array
.splice()
ー changes the contents of an array by removing the existing items or adding new items
.shift()
ーremoves the first item from an array
.unshift(item)
ー adds the item to the front of an array and returns the new length of the array
let favoriteColors = ['blue', 'white', 'baby pink'];
favoriteColors.push('light gray');
// The list now contains 4 items
favoriteColors.pop();
// The list now contains 3 items
console.log(favoriteColors.join());
// blue,white,baby pink
console.log(favoriteColors.slice(0, 2);
// ['blue', 'white']
favoriteColors.splice(1, 1, 'red');
// replaces 1 item at 1st index
console.log(favoriteColors);
// ['blue', 'red']
console.log(favoriteColors.shift());
// ['red']
favoriteColors.unshift('blue');
// the list now contains: blue, red