Get Methodical - Using Array Methods in JavaScript

One of the most powerful features of an Array is the ability to use its built in methods. A method is a built-in function that acts upon an object, like an Array. A useful method of an Array to know is the 'toString()' method which converts the values of an Array to a comma delimited string:

One issue you can see above is that there is no space after each comma. You can get a better result by using the join() method. The join() method allows you to declare what the separation delimiter will be:

Now, if you are like me, the little fact that my list is grammatically incorrect (no 'and' before the last item), might drive you crazy. But, there is trick we can use to polish that up. We turn to the pop() and push() methods for this. The pop() method will remove and return the last value in the Array, and the push() method will add a new value at the end of the Array. Take a look:

One point to remember, when we pop() the Array it removes the last value, so without putting the value back using push() we would not have the original data.

Similar to pop() and push() are shift() and unshift(). The shift() method removes and returns the first value in the Array and unshift() adds a value at the beginning:

If you would like to learn more about using the Array Method and the JavaScript language visit JavaScript Training Classes on our website for some excellent classes on the subject.

Onsite JavaScript training

Through our network of local trainers we deliver onsite JavaScript classes right across the country. Obtain a quote for onsite JavaScript training.

To view a sample of our past students testimonials, please click on the following link: Javascript testimonials.