1
1
Arrays
2
- Arrays are lists of ordered , stored data . They can hold items that are of any data type .
2
+ -- Arrays are lists of ordered , stored data . They can hold items that are of any data type .
3
3
Arrays are created by using square brackets , with individual elements separated by commas .
4
4
5
5
// An array containing numbers
6
6
const numberArray = [ 0 , 1 , 2 , 3 ] ;
7
7
8
8
// An array containing different data types
9
9
const mixedArray = [ 1 , 'chicken' , false ] ;
10
- Index
10
+
11
+
12
+ -- Index
11
13
Array elements are arranged by index values , starting at 0 as the first element index . Elements can be accessed by their index using the array name , and the index surrounded by square brackets .
12
14
13
15
// Accessing an array element
14
16
const myArray = [ 100 , 200 , 300 ] ;
15
17
16
18
console . log ( myArray [ 0 ] ) ; // 100
17
19
console . log ( myArray [ 1 ] ) ; // 200
18
- console . log ( myArray [ 2 ] ) ; // 300
20
+ console . log ( myArray [ 2 ] ) ; // 300
21
+
22
+
23
+ -- Mutable
24
+ JavaScript arrays are mutable , meaning that the values they contain can be changed .
25
+
26
+ Even if they are declared using const , the contents can be manipulated by reassigning internal values or using methods like . push ( ) and . pop ( ) .
27
+
28
+ const names = [ 'Alice' , 'Bob' ] ;
29
+
30
+ names . push ( 'Carl' ) ;
31
+ // ['Alice', 'Bob', 'Carl']
32
+
33
+
34
+ -- Property . length
35
+ The . length property of a JavaScript array indicates the number of elements the array contains .
36
+
37
+ const numbers = [ 1 , 2 , 3 , 4 ] ;
38
+
39
+ numbers . length // 4
40
+
41
+
42
+ -- Method . push ( )
43
+ The . push ( ) method of JavaScript arrays can be used to add one or more elements to the end of an array . . push ( ) mutates the original array returns the new length of the array .
44
+
45
+ // Adding a single element:
46
+ const cart = [ 'apple' , 'orange' ] ;
47
+ cart . push ( 'pear' ) ;
48
+
49
+ // Adding multiple elements:
50
+ const numbers = [ 1 , 2 ] ;
51
+ numbers . push ( 3 , 4 , 5 ) ;
52
+
53
+
54
+ -- Method . pop ( )
55
+ The . pop ( ) method removes the last element from an array and returns that element .
56
+
57
+ const ingredients = [ 'eggs' , 'flour' , 'chocolate' ] ;
58
+
59
+ const poppedIngredient = ingredients . pop ( ) ; // 'chocolate'
60
+ console . log ( ingredients ) ; // ['eggs', 'flour']
61
+
62
+
0 commit comments