DEV Community

iBrendan!
iBrendan!

Posted on

Dev Journal - Day 3 - Odin Project - JS Fundamentals 4 - Arrays

Arrays

  • Arrays are a special type of variable used to store multiple values like strings, HTML elements, or even other arrays.
  • Those values can then be accessed by referring to their index number.
  • Javascript arrays are zero indexed, meaning that the first element or item in an array is at index 0, the second is at index 1, and the final item or element is always one less than the length of the array.

Syntax

  • An array is preferably created in the array literal format, declared with the const keyword. Example,
const provinces = [“Alberta, “British Columbia”, “Ontario”];
Enter fullscreen mode Exit fullscreen mode
  • Note: Arrays can also be created in the new keyword format below. though this is discouraged for readability and execution speed reasons.
const provinces = new Array(“Alberta, “British Columbia”, “Ontario”) 
Enter fullscreen mode Exit fullscreen mode

Manipulating Array Elements

  • An array element can be accessed by its index. Example "provinces[1]" will access “British Columbia” in the province array above.
  • Array elements can be changed by assigning a new value to the index. So in our example, I can change the value of the second element, British Columbia (index 1) to a different value by
const provinces = ["Alberta", "British Columbia", "Ontario"];
provinces[1] = "British Columbia";
provinces[1] = "Quebec";
console.log(provinces); //[“Alberta, “Quebec”, “Ontario”]
Enter fullscreen mode Exit fullscreen mode

Array Properties

  • Length property returns the length of an array, or the total number of items in that array, and is always one more than the index of the highest array value
 const provinces = ["Alberta", "British Columbia", "Ontario"];
 console.log (provinces.length] //3
Enter fullscreen mode Exit fullscreen mode
  • Sort property sorts the array
const provinces = ["Alberta", "British Columbia", "Ontario"];
console.log(provinces.sort()); //“Alberta”, “Ontario”, “British Columbia”]
Enter fullscreen mode Exit fullscreen mode

Array Methods
Learned about using array with the following methods/operations:

  • Array.isArray() to determine if an argument is an array. Returns "true", or false otherwise
  • Array.push(...items) adds items to the end of the array and returns the new length of the array.
  • Array.pop() removes the element from the end and returns that element.
  • Array.shift() removes the element from the beginning of the array and returns it.
  • Array.unshift(...items) adds items to the beginning of the array
  • Array.splice() method adds new items to an array.
  • Array.slice() method slices out a piece of an array.

References

  1. The Odin Project
  2. Javascript.info - Arrays

Top comments (0)