Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Array Elements Can Be Objects

JavaScript variables can take the form of objects. Arrays are considered a distinct subtype of objects.

As a result, you can encompass variables of diverse types within the same array.

This includes objects, functions, and even arrays within an array.

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods

The true power of JavaScript arrays lies in their inherent array properties and methods.

cars.length   // Returns the number of elements
cars.sort()   // Sorts the array

The upcoming chapters delve into array methods.

 

The length Property

The length property of an array yields the array’s length, indicating the number of elements it contains.

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];
let length = fruits.length;
The length property is consistently one more than the highest index present in the array.

Accessing the First Array Element

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];
let fruit = fruits[0];

Accessing the Last Array Element

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];
let fruit = fruits[fruits.length – 1];

Looping Array Elements

A method to iterate through an array is by employing a for loop.

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];
let fLen = fruits.length;

let text = “<ul>”;
for (let i = 0; i < fLen; i++) {
  text += “<li>” + fruits[i] + “</li>”;
}
text += “</ul>”;

Another option is to utilize the Array.forEach() function:

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];

let text = “<ul>”;
fruits.forEach(myFunction);
text += “</ul>”;

function myFunction(value) {
  text += “<li>” + value + “</li>”;
}