{"id":8909,"date":"2019-01-27T09:30:05","date_gmt":"2019-01-27T14:30:05","guid":{"rendered":"https:\/\/www.carnaghan.com\/?p=8909"},"modified":"2021-03-25T20:56:51","modified_gmt":"2021-03-26T00:56:51","slug":"javascript-arrays-properties-and-methods","status":"publish","type":"post","link":"https:\/\/www.carnaghan.com\/javascript-arrays-properties-and-methods\/","title":{"rendered":"JavaScript Arrays – Properties and Methods"},"content":{"rendered":"

We are going to cover some of the most commonly used properties and methods in JavaScript, for working with arrays. There are a lot of other methods which are not covered here, including newer ES6 methods. The goal here is to get you started working with arrays and gaining an understanding of the fundamental ways we can access and manipulate data. The table below summarizes the various methods we will cover in this lesson:<\/p>\n\n\n\n\n\n\n\n\n\n
length property<\/td>\nSets or returns the number of elements in an array<\/td>\n<\/tr>\n
find methods<\/td>\nReturns the value (find) or index (findIndex, indexOf) of the first element in an array<\/td>\n<\/tr>\n
sort, reverse, and compare<\/td>\nSorts, reverses, and compares the elements of an array<\/td>\n<\/tr>\n
push and pop<\/td>\nAdds (push) or removes (pop) new elements to the end of an array, and returns the new length<\/td>\n<\/tr>\n
unshift and shift<\/td>\nAdds (unshift) or removes (shift) new elements to the beginning of an array, and returns the new length<\/td>\n<\/tr>\n
splice and slice<\/td>\nAdds\/Removes elements from an array (splice) or selects a part of an array, and returns the new array (slice)<\/td>\n<\/tr>\n
concat<\/td>\nJoins two or more arrays, and returns a copy of the joined arrays<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

For a more complete list, please be sure to check out the W3 Schools JavaScript Array Reference<\/a>.<\/p>\n

The length property<\/h2>\n

The length property is extremely useful to determine the number of elements in a given array. In your console try entering students.length<\/strong>. You will be presented with the number of elements in our students array (in this case 4). Because length is a property, no arguments are needed here nor are empty brackets. The property simply returns the number of elements as expected and does not provide additional functionality.<\/p>\n

The find, findIndex, and indexOf methods<\/h2>\n

The find method can be used to locate an element within your array. It works by passing in a callback function to the find array method. If you recall in our earlier lesson on JavaScript Functions, we discussed that functions can be defined as variables. Callback functions (sometimes referred to as higher-order functions) are simply functions or variables defined as a function expression, that have been passed into another function as an argument. The array find method expects a function passed as an argument, which we can do. This is better illustrated through an example.<\/p>\n