Arrays Flashcards
What is an array?
An array is a collection of data, and can be strings, numbers, booleans or a mix thereof.
What will the following console.log return? const catNames = ['Clawdia', 'Special Agent Mittens', 'Pixel', 'Jennifur', 'Linux']; console.log(catNames.length);
There are 5 items in the array, and count starts at 0.
Arrays always start at __
Zero
What method would can be used to tell us the value of the last index in an array?
The .length method
Ex: const dogNames = ['Kareem Abdul Ja-Bark', 'Mary Puppins', 'Salvador Dogi', 'Sherlock Bones', 'Bark Twain']; console.log(dogNames[dogNames.length - 1]);
Will return ‘Bark Twain,’ the last name in the array.
What do .push and .pop do?
.push adds an item or items to the end of an array (think ‘the items are pushed into the array container’)
.pop removes an item or items from the end of the array (think “Pop! It’s gone!”)
const cheeses = ['Gouda', 'Cheddar', 'Gruyere', 'Brie', 'Parmesan']; cheeses[0] = 'String'; console.log(cheeses);
What are we doing here, and what will the console.log return?
We are reassigning the 0 place in the index to now read ‘String’ instead of ‘Gouda’.
It will return ‘String’, ‘Cheddar’, ‘Gruyere’, ‘Brie’, ‘Parmesan’
What do .shift and .unshift do?
.unshift will add a new index at the beginning (the front) of an array.
.shift will remove the first index in the array
What is a JavaScript method?
A method is an action that can be performed on an object.
True or False - the following declaration is a valid array?
let newArr = [1, 2, 3, “Hello World, 4.25, true];
True
An array can contain numbers, strings, booleans and floating point numbers (decimals)
What does the .slice method do?
.slice is a way to copy a given part of an array.
It is assigned using 2 values indicating from where we start and to where we end.
Important Note: the use of copy here is important. .slice() It does not change the original array.
let fishNames = [‘Tank Sinatra’, ‘Harley Fin’, ‘Bait’, ‘Kosher’, ‘Anne Chovy’, ‘DJ Great-White, ‘Squirt’];
let fishNameSlice = fishNames.slice(1, 3);
console.log(fishNameSlice);
What names will fistNameSlice return?
“Harley Fin” and “Bait”
The .slice method function will return the 1st until the 3rd index in the array, so in this case, it will create a new array with the names “Harley Finn” and “Bait”.
Describe the .splice() method.
What 2 functions can it do?
.splice() is a way to change the original array. It can add or remove items to the array.
Important Note: the use of change is important here. This method changes the array
let index = [1, 2, 3, 4, 5, 6, 7];
index. splice(3);
console. log(index);
What will this return?
“1, 2, 3”
Note: If the second parameter (telling the slice when to end) isn’t given it removes everything after that index.