Methods and Properties
Array Methods and Properties
In JavaScript, arrays have their built-in variables and functions which are defined as methods and properties of an array.
Property |
Description |
---|---|
Constructor |
returns a function that helps in creating the array object |
Length |
returns the number of elements in an array |
prototype |
Mainly helps in adding methods and properties to an object |
The Length Property
An array’s length property returns the number of elements in an array. The syntax of the property is defined as array name.property.
Code:
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java","HTML"];
document.write(lang.length);
</script>
</body>
</html>
Output:
Array Methods
Array Methods are defined as actions which are used in order to access and manipulate data of an array.
Method |
Description |
---|---|
concat() |
Returns a new array which is the union of two or more arrays |
pop() |
Removes the last element of an array and return that element |
push() |
Add new elements to the end of an array and returns new length |
reverse() |
Reverse the order of the elements in an array |
toString() |
Helps in converting an array to a string |
join() |
Joins all the elements of an array into a string |
indexOf() |
Search for an element in an array and return the position |
shift() |
Removes the first element of an array and return that element |
slice() |
Extracts a part of an array and return that array |
sort() |
Sorts the elements of an array |
The concat () method
An Array’s concat() method returns a new array which is a union of the values of two arrays.
Code:
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java"];
var lang1 = ["HTML", "CSS"]
var languages = lang.concat(lang1);
document.write(languages);
</script>
</body>
</html>
Output:
Pop Method
The pop method mainly removes the last element of an array and further returns the element value.
Code:
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java","HTML"];
document.write("Array before popping: " +lang + "<br>");
var x=lang.pop();
document.write("Array after popping: " +lang + "<br>");
document.write("The popup element : " +x + "<br>");
</script>
</body>
</html>
Output:
The Push Method
Push method mainly adds a new element to an array at its very end.
Code:
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java"];
document.write("Array before pushing: " +lang + "<br>");
lang.push("HTML");
document.write("Array after pushing: " +lang + "<br>");
</script>
</body>
</html>
Output:
The Reverse Method
The reverse method mainly reverses the order of the elements of an array.
Code:
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java","HTML"];
document.write("Array before reverse method: " +lang + "<br>");
lang.reverse();
document.write("Array after reverse method: " +lang + "<br>");
</script>
</body>
</html>
Output: