Page 234 - Web_Application_v2.0_C12_Fb
P. 234
2.11 ARRAYS IN JAVASCRIPT
Arrays are versatile structures designed to store First Element (at Fifth Element (at
multiple values of the same type within a single index 0) index 4)
container. In JavaScript, arrays can accommodate
various data types, such as numbers, strings, objects, First Index A R R A Y S
and even nested arrays. They operate on a zero-based 0 1 2 3 4 5 Indices
indexing system, meaning the first item is accessible Negative index
using index 0, the second with index 1, and so forth.
This indexing approach makes arrays an efficient tool for organizing and managing data.
An array is a special variable, with the capacity to hold several values. Syntax:
const array_name = [element1, element2, ...];
It is a common practice to declare arrays with the const keyword.
Creating Arrays
Different ways for creating an array are as follows:
The simplest way of creating an array is using the array literal:
Here we simply assign a variable to values written in square bracket [ ], separated with commas.
For example:
const animals = ["lion", "tiger", "giraffe", "elephant"];
You can also create a blank array, and then specify the elements:
For example:
const birds = [];
birds[0]= "pigeon";
birds[1]= "sparrow";
birds[2]= "eagle";
By using the new keyword with array, you can create an array
For example:
const currency = new Array("Dollar", "Yen", "Pound");
Accessing Array Elements
Array elements can be accessed using the respective index value.
lion tiger giraffe elephant
Index value 0 1 2 3
Accessing the First Element of an Array
To access the first element of an array, you simply use index 0. JavaScript arrays are zero-indexed, meaning
the first element is at index 0.
For example:
const array = [10, 20, 30, 40, 50];
// Accessing the first element (index 0)
var firstElement = array[0];
console.log(firstElement); // Output: 10
232 Touchpad Web Applications (Ver. 2.0)-XII

