Arrays in JavaScript

by danielkwood

HTML

<html>
    <head>
        <title>Arrays</title>
        <script src="script.js"></script>
    </head>
    <body>
    </body>
</html>

JavaScript

// How to create an empty array
var fruits = [];

// How to add elements to an existing array one-by-one
fruits[0] = "apple";
fruits[1] = "banana";
fruits[2] = "orange";

// Each element has an index (position)
// Indexing starts from 0

// How to create an array with elements in it
var users = ["joe", "sally", "max", "alice"];

// How to modify an existing element in an array
users[3] = "tim";

// How to add an element to an array
users[4] = "lisa";

// How to access individual elements from an array
console.log(users[0]); // this will display "joe"
console.log(users[1]); // this will display "sally"
console.log(users[4]); // this will display "lisa"