Course Content
Introduction to JavaScript
Introduction to JavaScript
What Are Arrays?
An array is simply an ordered collection of variables.
Defining an Array
The general syntax of defining an array is:
js
We can declare an empty array as well:
python
Arrays are useful when we need to store multiple values in a single variable instead of creating separate variables for each value.
This makes data easier to organize and manipulate. For example, we can store the names of the class students in an array:
We can output all the elements of an array by simply using it's name in a console.log statement:
let students = [ "Emma", "Alex", "Chris" ]; console.log(students); let emptyArray = []; console.log(emptyArray);
Indexing
We can access an element at a specific position in the array by indexing.
The syntax for indexing is:
js
Here arrayName
is the name of the array, and index
refers to the position of the element in the array.
The index values start from 0
, which means the first element always has an index 0
.
let students = [ "Emma", "Alex", "Chris" ]; console.log(students[0]); // Output: Emma console.log(students[1]); // Output: Alex console.log(students[2]); // Output: Chris
Using an invalid index returns undefined
:
let students = [ "Emma", "Alex", "Chris" ]; console.log(students[-1]); // Output: undefined console.log(students[4]); // Output: undefined
1. What is an array in JavaScript?
2. Which of the following is the correct way to declare an array?
3. What does the following code output?
4. What will be the output of the following code?
Thanks for your feedback!