Data can be stored and accessed in many ways. You already know some common JavaScript data structures — arrays and objects.
In this Basic Data Structures posts, you'll learn more about the differences between arrays and objects, and which to use in different situations. You'll also learn how to use helpful JS methods like
splice()
andObject.keys()
to access and manipulate data.
Use an Array to Store a Collection of Data
Here is an example of the simplest implementation of an array data structure. This is known as a one-dimensional array, meaning it only has one level, or that it does not have any other arrays nested within it.
let array = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);
The `console.log` call displays `7`.
- All arrays have a length property, which as shown above, can be very easily accessed with the syntax Array.length.
- Notice it contains booleans, strings, and numbers, among other valid JavaScript data types.
Access an Array's Contents Using Bracket Notation
- We have the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
- When we define a simple array as seen below:
let myArray = ["a", "b", "c"];
- In an array, each array item has an index. It is important to note, that JavaScript arrays are zero-indexed, meaning that the first element of an array is actually at the zeroth position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as bracket notation. *Ex:
let ourVariable = myArray[0];
Now
ourVariable
has the value ofa
.In addition to accessing the value associated with an index, you can also set an index to a value using the same notation:
myArray[1] = "e";
- Using bracket notation, we have now reset the item at index 1 from the string
b
, to 'e. Now
myArrayis
["a", "e", "c"]`.
Top comments (0)