How to create and use an array
To create an array in JavaScript, you can use the following syntax:
var myArray = [];
This creates an empty array. You can then add elements to the array using the push()
method:
myArray.push(1);
myArray.push("Hello");
myArray.push(true);
Accessing Array Elements
You can access the elements of an array using their index. The index of an element is its position in the array, starting from 0.
For example, to access the first element of the array myArray
, you would use the following code:
var firstElement = myArray[0];
Examples in JavaScript
Here are some examples of arrays in JavaScript:
// An array of numbers
var numbers = [1, 2, 3, 4, 5];
// An array of strings
var strings = ["Hello", "World", "Goodbye"];
See the Pen Introduction to Algorithms and Data Structures: Pen 1 by TumkurLab (@tumkurlab) on CodePen.