Skip to content

Commit a09a129

Browse files
authored
Update arrays.md
Accessing the last item
1 parent 42d27b5 commit a09a129

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

notes/javascript/datatypes/arrays.md

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,9 @@ Like other languages, individual array values can be accessed by their index. Ar
3131
var arr = ["a", "b", "c", "d"]
3232

3333
arr[0] //> "a"
34-
3534
arr[1] //> "b"
36-
3735
arr[2] //> "c"
38-
3936
arr[3] //> "d"
40-
4137
arr[4] //> undefined
4238
````
4339

@@ -58,11 +54,8 @@ It is possible to get the index value of any item in the array. In the event the
5854
var arr = ["a", "b", "c", "b", "a"]
5955

6056
arr.indexOf("a") //> 0
61-
6257
arr.indexOf("b") //> 1
63-
6458
arr.indexOf("c") //> 2
65-
6659
arr.indexOf("z") //> -1 (applies to any item not found in the array)
6760
````
6861

@@ -72,11 +65,21 @@ Counting the number of items in an array:
7265

7366
```` js
7467
var arr = ["a", "b", "c", "d"]
68+
7569
arr.length //> 4
7670
````
7771

7872

79-
Checking to see if an item is (or is not) in the array:
73+
One trick for dynamically accessing the last item in an array (no matter how many there are) is to leverage the length of the array and subtract one, to arrive at the index of the last item:
74+
75+
```js
76+
var arr = ["a", "b", "c", "d"]
77+
78+
arr[arr.length - 1] //> "d"
79+
```
80+
81+
82+
Checking to see if an item is in the array, or not:
8083

8184
````js
8285
var arr = ["a", "b", "c", "d"]
@@ -95,7 +98,6 @@ Adding an item to the end of an array:
9598
var arr = ["a", "b", "c", "d"]
9699

97100
arr.push("e")
98-
99101
arr //> ["a", "b", "c", "d", "e"]
100102
````
101103

0 commit comments

Comments
 (0)