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>