Arrays js Flashcards

1
Q

What is an array?

A

An array is a collection of items of the same data type stored at contiguous memory locations.

This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can we access data in arrays?

A

By using indexes var[0].

We can access the data inside arrays using indexes.

Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do we modify Array data with indexes?

A

Unlike strings, the entries of arrays are mutable and can be changed freely, even if the array was declared with const.
Example

const ourArray = [50, 40, 30];
ourArray[0] = 15;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the push method?

A

An easy way to append data to the end of an array is via the push() function.

.push() takes one or more parameters and “pushes” them onto the end of the array.

Examples:

const arr1 = [1, 2, 3];
arr1.push(4);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does the pop method?

A

Another way to change the data in an array is with the .pop() function.

.pop() is used to pop a value off of the end of an array. We can store this popped-off value by assigning it to a variable. In other words, .pop() removes the last element from an array and returns that element.

Any type of entry can be popped off of an array - numbers, strings, even nested arrays.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the shift method?

A

pop() always removes the last element of an array. What if you want to remove the first?

That’s where .shift() comes in. It works just like .pop(), except it removes the first element instead of the last.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what does unshift method?

A

Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the array.

.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly