Arrays Recap
In this chapter, we learned how to work with arrays in JavaScript. We discovered that:
- We can create arrays using square brackets
[]
and elements separated by commas. For example:const list = [1, 2, 3, 3];
. - We access array elements using their indices, which start at 0. For example:
console.log(list[0]);
prints the first element of thelist
array. - We can easily change array elements using their indices:
- For example:
list[3] = 4;
sets the fourth element of thelist
array to 4. - Using the
push()
method, we can add new elements to the end of the array. For example:list.push(5)
adds the value 5 to the end of the array. - Using the
pop()
method, we can remove the last element from the array. For example:lastElement = list.pop()
removes the last element from thelist
array and stores its value in thelastElement
variable. - Using the
length
property, we can find out the number of elements in the array. For example:numberOfElements = list.length
stores the number of elements in thelist
array in thenumberOfElements
variable. - Arrays can contain other arrays as their elements, which allows us to create nested arrays. For example:
nestedArray = [[1, 2], [3, 4], [5, 6]]
. - Text strings can also be considered arrays of characters, which we can access using their indices. For example:
const text = "JavaScript";
andconst firstChar = text[0];
stores the first character"J"
in thefirstChar
variable.
Congratulations on completing the lesson on arrays! In the next lesson, we will look at loops and their use in JavaScript. Get ready for the next step in your programming adventure!
Instructions
When you are ready, proceed to the next lesson!
Start programming for free
10/10