An array is a variable that can store more than one data (strings or numbers). You use indexing number to access data from a particular index of an array. An array reserves memory blocks in the ram according to its data (indexes numbers) to stores its indexes data serially, but an ordinary variable has only one memory block to store data.
How array stores values: Values in an array are stored by indexing numbers in the ram, so that, if we want to print any value, then simply bypassing indexing number we can examine/print stored data one by one. The first value of the array starts with indexing number 0
Ordinary variable:
var x = "HTML";
Array variable:
var a = ["HTML","CSS","JAVASCRIPT",8,"Jaischool",'j'];
How To Create An Array?
Like an ordinary array use var keyword and after that, give its name. Use big bracket to store data, and each value in the array must be separated by a comma.
- String should be surrounded by a double quote.
- Characters (single letter) should be surrounded by a single quote.
- Put numbers without any single or double quote.
Example-
var names = ["Ram",9,"Shyam",'J'];
How to make empty an Array?
<!DOCTYPE html>
<html>
<head>
<title>Javascript Array</title>
</head>
<body>
<center>
<button onclick="demo()">Print</button>
<button onclick="empty_array()">Empty array</button>
</center>
<script>
var a = ["HTML","CSS","JAVASCRIPT",8,"Jaischool",'j'];
function demo()
{
alert(a);
}
function empty_array()
{
a = [];
}
</script>
</body>
</html>
How To Print A Particular Value From Array?
Below code will print Java-script because in the second index's value of array is Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Javascript Array</title>
</head>
<body>
<center>
<button onclick="demo()">Click</button>
</center>
<script>
function demo()
{
var a = ["HTML","CSS","JAVASCRIPT",8,"Jaischool",'J'];
alert(a[2]);
}
</script>
</body>
</html>
Other Articles
- || Output methods in JS
- || Check browser compatibility for service worker
- || Javascript which and button property
- || print all CSS properties with their default value in JS
- || Print array’s max number
- || prevent the form from being submitted
- || Change the HTML element class in JS
- || Know the width of the window while it is resizing
Publish A Comment