Array in js

Yoseob Shin·2022년 3월 29일
0

javascript

목록 보기
9/24
post-thumbnail
post-custom-banner

Organizing and storing data is a foundational concept of programming.

One way we organize data in real life is by making lists
example:
New Year's Resolutions:

  1. Keep a journal
  2. Take a falconry class
  3. Learn to juggle

in javascript code:

let newYearsResolutions = ['Keep a journal', 'Take a falconry class', 'Learn to juggle'];

Arrays are JavaScript’s way of making lists. Arrays can store any data types (including strings, numbers, array, object and booleans). Like lists, arrays are ordered, meaning each item has a numbered position.

Accessing Elements

Each element in an array has a numbered position known as its index. We can access individual items using their index, which is similar to referencing an item in a list based on the item’s position.

Arrays in JavaScript are zero-indexed, meaning the positions start counting from 0 rather than 1.

You can also access individual characters in a string using bracket notation and the index.

const hello = 'Hello World';
console.log(hello[6]);
// Output: W
  • Returns undefined when accessing an index beyond the last element.

Update Elements in array

let seasons = ['Winter', 'Spring', 'Summer', 'Fall'];
 
seasons[3] = 'Autumn';
console.log(seasons); 
//Output: ['Winter', 'Spring', 'Summer', 'Autumn']

seasons[3] = 'Autumn'; tells our program to change the item at index 3 of the seasons array to be 'Autumn' instead of what is already there.

Arrays with let and const

Variables declared with the const keyword cannot be reassigned. However, elements in an array declared with const remain mutable. Meaning that we can change the contents of a const array, but cannot reassign a new array or a different value.

The .length property

One of an array’s built-in properties is length and it returns the number of items in the array.

  • It returns a number of elements inside an array.
const newYearsResolutions = ['Keep a journal', 'Take a falconry class'];
 
console.log(newYearsResolutions.length);
// Output: 2

The .push() Method

It is a built-in JavaScript array methods that makes working with arrays easier.

push() allows us to add items to the end of an array. Here is an example of how this is used:

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'];

.push() is a function and one that JavaScript allows us to use right on an array.

Notice that .push() changes, or mutates, itemTracker. You might also see .push() referred to as a destructive array method since it changes the initial array.

The .pop() Method

Another array method, .pop(), removes the last item of an array.

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
  • .pop() does not take any arguments, it simply removes the last element of newItemTracker.
  • .pop() returns the value of the last element. In the example, we store the returned value in a variable removed to be used for later.
  • .pop() is a method that mutates the initial array.

Some arrays methods that are available to JavaScript developers include: .join(), .slice(), .splice(), .shift(), .unshift(), indexOf()and .concat() amongst many others.

.splice()

Array.prototype.splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

  • Return value
    An array containing the deleted elements.
    If only one element is removed, an array of one element is returned.
    If no elements are removed, an empty array is returned.

Destructive(mutating) array method

  • .shift(), .unshift(), push(), pop(), splice()

Non Destructive array method

  • .join(), .slice(), indexOf(), .concat(), etcetc....

Arrays and Functions

const flowers = ['peony', 'daffodil', 'marigold'];
 
function addFlower(arr) {
  arr.push('lily');
}
 
addFlower(flowers);
 
console.log(flowers); // Output: ['peony', 'daffodil', 'marigold', 'lily']

when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass by reference since what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.

interesting article to read --> Pass-by-value vs pass-by-reference.

Nested Arrays

When an array contains another array it is known as a nested array.

const nestedArr = [[1], [2, 3]];
 
console.log(nestedArr[1]); // Output: [2, 3]

const nestedArr2 = [[1], [2, 3]];
 
console.log(nestedArr2[1]); // Output: [2, 3]
console.log(nestedArr2[1][0]); // Output: 2

nestedArr[1] will grab the element in index 1 which is the array [2, 3]. Then, if we wanted to access the elements within the nested array we can chain, or add on, more bracket notation with index values.

we have two bracket notations chained to nestedArr. We know that nestedArr[1] is the array [2, 3]. Then to grab the first element from that array, we use nestedArr[1][0] and we get the value of 2.

Review

  • Arrays are lists that store data in JavaScript.
  • Arrays are created with brackets [].
  • Each item inside of an array is at a numbered position, or index, starting at 0.
  • We can access one item in an array using its index, with syntax like: myArray[0].
  • We can also change an item in an array using its index, with syntax like myArray[0] = 'new string';
  • Arrays have a length property, which allows you to see how many items are in an array.
  • Arrays have their own methods, including .push() and .pop(), which add and remove items from an array, respectively.
  • Arrays have many methods that perform different tasks, such as .slice() and .shift(), you can find documentation at the Mozilla Developer Network website.
  • Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
  • Variables that contain arrays can be declared with let or const. Even when declared with const, arrays are still mutable. However, a variable declared with const cannot be reassigned.
  • Arrays mutated inside of a function will keep that change even outside the function.
  • Arrays can be nested inside other arrays.
  • To access elements in nested arrays chain indices using bracket notation.

Ref:

Pass-by-value vs pass-by-reference.

profile
coder for web development + noodler at programming synthesizers for sound design as hobbyist.
post-custom-banner

0개의 댓글