Declaring arrays
- Node.js course
- Beginner
- Lesson 53/116
- 4 min
Learn to declare and initialize arrays with [].
Declaring arrays
To hold several values in a single variable you use an array. In JavaScript an array is declared with comma-separated values inside square brackets []: const colors = ["red", "blue", "green"];.
Each value in an array is called an element. An array may hold zero, one or more elements. An empty array is created with []; you can add elements later with push. Strings, numbers, booleans and even objects can all live in the same array; but good practice keeps elements of a similar type.
The length property
The .length property tells how many elements an array has. [10, 20, 30].length evaluates to 3. length is a property, not a method; there is no parenthesis at the end.
length is especially useful for loop bounds: with for (let i = 0; i < arr.length; i++) you walk all elements. An empty array has length 0. Although length can be set directly, it is uncommon; to resize an array you use methods like push, pop or splice.
Practice Declare and print the array
Declare a variable colors and set its value to ["red", "blue", "green"]. Then print colors.length with console.log. The output on a single line must be 3.
Starter code
// Declare colors and print its lengthSample solution
const colors = ["red", "blue", "green"];
console.log(colors.length);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid array declaration?
const arr = ...;- const arr = [1, 2, 3]; Correct answer
- const arr = {1, 2, 3};
- const arr = (1, 2, 3);
- const arr = <1, 2, 3>;
Explanation: Arrays are declared inside square brackets [].
2 Write the array literal
const colors = ____;
const colors = ["red", "blue"];
Explanation: An array is written with square brackets.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
[] |
Empty array |
[1, 2, 3] |
Three-element array |
.length |
Element count |
["a"] |
Single-element array |