What is role of an array object in JS and why are we use the array?

Asked 19-Jul-2021
Viewed 198 times

0

1 Answer


1

An array is a special type of variable, which can hold more than one value at a time. If you have a list of items (a list of fruits names, for example), storing the fruits in single variables could look like this.
let fruit1 = 'apple';

let fruit2 = 'banana';
let fruit3 = 'orange';
However, what if you want to loop through the fruits and find a specific one? And what if you had not 3 fruits, but 300. The solution is an array. An array can hold many values under a single name, and you can access the values by referring to an index number.
There are two way to create array in js.
• By literals
• By new keyword of array constructor
By Literals
Syntax
 const array_name = [item1, item2, ...]; 
Example
<!DOCTYPE html>

<html>
<body>
<h2>JavaScript Arrays</h2>
<p id='demo1'></p>
<p id='demo2'></p>
<p id='demo3'></p>
<script>
const fruit1 = ['apple','banana','orange'];
document.getElementById('demo1').innerHTML = fruit1;
const fruit2 = [
  'apple',
  'banana',
  'orange'
];
document.getElementById('demo2').innerHTML = fruit2;
const fruit3 = [];
fruit3[0]= 'apple';
fruit3[1]= 'banana';
fruit3[2]= 'orange';
document.getElementById('demo3').innerHTML = fruit3;
</script>
</body>
</html>
By new keyword
Syntax
 Variable-name= new Array (data1, data2, data3, ----);
Example
<!DOCTYPE html>

<html>
<body>
<h2>JavaScript Arrays</h2>
<p id='demo'></p>
<script>
const cars = new Array('Saab', 'Volvo', 'BMW');
document.getElementById('demo').innerHTML = cars;
</script>
</body>
</html>