Javascript (Arrays) Flashcards
What are arrays?
An array is a collection of elements. Arrays are JavaScript’s way of making lists. Arrays can store any data types (including strings, numbers, and booleans). Arrays are also ordered (each item has a numbered position)
What are array literals?
Array literals create an array by wrapping items in square brackets [].
What are the ways to create an array.
- Using array literals
What is the content inside of an array called?
An element, code block
What is an index?
An index is a numbered position for an element. Each element in an array will have a numbered position.
Arrays are zero-indexed. What does this mean?
Zero-indexed means that the positions start counting from 0 rather than 1. Therefore, the first item in an array will be at position 0.
How can we update an element in an array?
We can update an element in an array by using the following syntax:
variableName[3] = ‘new value’;
What is the difference between using let and const when working with arrays?
When we use the let variable when working with arrays we can reassign a new array and update an element in the array. With const variables we can update an element in an array but we can not reassign a new array.
.length
The .length property is one of an array’s built in properties. It returns the number of items in the array.
Ex:
const newYearsResolutions = [‘Keep a journal’, ‘Take a falconry class’];
console.log(newYearsResolutions.length);
// Output: 2
.push()
The .push() method allows you to add items to the end of an array. The .push() changes, or mutates, the array. This method is also called a destructive array method since it changes the initial array. When we add this method to an array we can call the array like we would a function.
Ex:
const itemTracker = [‘item 0’, ‘item 1’, ‘item 2’];
itemTracker.push(‘item 3’, ‘item 4’);
console.log(itemTracker);
// Output: [‘item 0’, ‘item 1’, ‘item 2’, ‘item 3’, ‘item 4’];
.pop()
The .pop method removes the last item in an array. It does not take any arguments. This method also mutates the array. The .pop() method also returns the value of the last element. We can store this in a variable to use later in the code.
Ex:
const newItemTracker = [‘item 0’, ‘item 1’, ‘item 2’];
const removed = newItemTracker.pop();
console.log(newItemTracker);
// Output: [ ‘item 0’, ‘item 1’ ]
console.log(removed);
// Output: item 2
.shift()
The .shift method removes and returns the first element of the array. All of the elements after it will shift down one place.
.unshift()
Adds one or more elements to beginning of array and returns new length.
.slice()
The .splice() method modifies an array by inserting, removing, and/or replacing array elements then returning an array of removed elements. The splice array is a shallow copy of the original array.
.indexOf()
The .indexOf() method returns the first index at which an element can be found. Returns -1 if the element is not found.