- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Arrays
JavaScript Arrays
JavaScript Arrays
A JavaScript array stores several values in a single variable.
Instead of one variable for each value, an array holds a whole list under one name.
Each value in the list is called an element.
Example
Example
javascript
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length);The array holds three values.
The output is 3.
What is an Array?
An array is an ordered list of values written inside square brackets.
The order is kept, so the first value stays first.
An array can hold any type of value, including other arrays.
Syntax
Syntax
javascript
const name = [value1, value2, value3];Separate the values with commas.
Creating an Array
The square bracket form is the one you will use almost every time.
Example
Example
javascript
const numbers = [10, 20, 30];
const empty = [];
console.log(numbers.length);
console.log(empty.length);An empty array has a length of 0.
The length Property
length tells you how many elements the array holds.
Example
Example
javascript
const colours = ["red", "green", "blue"];
console.log(colours.length);Because counting starts at 0, the last index is always length - 1.
Mixed Types
JavaScript does not force every element to be the same type.
Example
Example
javascript
const mixed = ["Ada", 36, true];
console.log(mixed.length);In real code it is usually clearer to keep one type per array.
Arrays Inside Arrays
An element can itself be an array, which gives you rows and columns.
Example
Example
javascript
const grid = [[1, 2], [3, 4]];
console.log(grid.length);
console.log(grid[0].length);Here the outer array has two rows, and each row has two values.
const Does Not Freeze an Array
const stops the variable being pointed at a new array.
The contents can still be changed.
Example
Example
javascript
const list = [1, 2];
list.push(3);
console.log(list.length);Pushing works; assigning a whole new array to list would not.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Arrays</title>
</head>
<body>
<h1>JavaScript Arrays</h1>
<p id="result"></p>
<script>
const fruits = ["Apple", "Banana", "Mango"];
document.getElementById("result").innerHTML =
"The list has " + fruits.length + " fruits";
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try adding a fruit:
Add another name to the list and watch the count change.
Important Points
- An array stores several values under one name.
- Values are written inside square brackets, separated by commas.
lengthgives the number of elements.- An array can hold mixed types and other arrays.
constprevents reassignment, not changes to the contents.
Conclusion
A JavaScript array keeps an ordered list of values in one variable.
Almost every program works with lists, so arrays appear everywhere.
Understanding arrays is the foundation for the methods in the rest of this section.
