Array methods
We have just seen the built-in length property. We also have a few built-in methods. Methods are functions on a certain object. Instead of holding a value, like properties, they perform actions. We will cover functions in-depth in Chapter 6, Functions. For now, all you need to know is that you can call methods and functions, and when you do, some code that is specified inside that function gets executed.
We just accidentally saw we could add elements using new indices. This is not the proper way to do it as it is easy to make mistakes and accidentally overwrite a certain value or skip a certain index. The right way is to do this with a special method. Similarly, we can also delete elements and sort the elements in the array.
Adding and replacing elements
We can add elements with the push()
method:
favoriteFruits = ["grapefruit", "orange", "lemon"];
favoriteFruits.push("tangerine");
The value gets added...