Page 235 - Web_Application_v2.0_C12_Fb
P. 235
Accessing the Last Element of an Array
To access the last element of an array, you can use array.length - 1 to get the index of the last element.
Another modern method is to use at() which allows negative indexing.
For example:
const array = [10, 20, 30, 40, 50];
// Accessing the last element using array.length - 1
var lastElement = array[array.length - 1];
console.log(lastElement); // Output: 50
Modifying Array Elements
You can modify array elements by directly assigning a new value to an index, or you can use array methods
to modify all or specific elements.
For example:
const array = [10, 20, 30, 40, 50];
// Modifying the element at index 2 (third element)
array[2] = 35;
console.log(array); // Output: [10, 20, 35, 40, 50]
Example 43: To demonstrate how to modifying array elements
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Accessing Array Elements</TITLE>
</HEAD>
<BODY TEXT="red">
<H2>Accessing array elements</H2>
<FONT COLOR=BLUE>
<SCRIPT>
const cars = ["Ferrari", "WagonR", "BMW"];
document.write("Element 2 is " + cars[1]);
//element values can be changed
cars[2]="Porsche";
document.write("<br> After Change the array now is "+"<br>");
document.write(cars[0]+"<br>");
document.write(cars[1]+"<br>");
document.write(cars[2]+"<br>");
</SCRIPT>
</FONT>
</BODY>
</HTML>
JavaScript Part 2 233

