DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Desiree
Desiree

Posted on • Updated on

Understanding Arrays in JavaScript...

What is an Array?

We can use Arrays to organise data in JavaScript by making lists. Arrays can store any data types (strings: "Hello!", integers: 5, booleans: false) and we can also use keywords (let or const) to declare a variable and save it to an array.

How does an Array work?

Arrays are represented by square brackets [ ] and content inside (elements). Every element within an Array has a numbered position known as index. This means the positions start counting from 0 rather than 1.

For example:

  1. Below, I have created an array called javaScript. javaScript is an array that has 3 elements. Alt Text
  2. The first element within an array is always at position [0]. The second element is at position [1] and the third element is at position [2].

  3. Logging javaScript[1] to the console will access the element at index 1. // output: arrays.

Other cool things we can do...

Did you know that we can also access individual characters in a string using bracket notations and the index?

For example:

let challenge = '100 days of Code';
console.log(challenge[10]);
//output: C

Did you know that we can update elements within an array?

For example:
Alt Text

Another cool thing are Array methods:

  1. For example, we can use avengerCharacters.push('Black Panther') to push the element into the array, meaning adding 'Black Panther' to the list.

  2. We can use avengerCharacters.pop('Iron Man') to pop the element out of the array, meaning removing 'Iron Man' from the list.

  3. Array methods are a cool, quick and easy way to complete tasks. You can find more methods and explanations of each here:
    https://www.w3schools.com/js/js_array_methods.asp#:~:text=%20JavaScript%20Array%20Methods%20%201%20Converting%20Arrays,delete%20may%20leave%20undefined%20holes%20in...%20More%20

    or here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Top comments (2)

Collapse
desireecodes_40 profile image
Desiree Author

Thanks for the feedback, I've made some corrections :)

DEV runs on 100% open source code known as Forem.

Β 
Contribute to the codebase or host your own.
Β 
Check these out! πŸ‘‡