Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Accessing Arrays with Named Indexes

Many programming languages support arrays with named indexes, known as associative arrays (or hashes).

However, JavaScript does not support arrays with named indexes.

In JavaScript, arrays use numeric (numbered) indexes.

Example

const person = [];
person[0] = “John”;
person[1] = “Doe”;
person[2] = 46;
person.length;       // person.length will return 3
person[0];           // person[0] will return “John”

In JavaScript, objects use named indexes.

If you use a named index to access an array, JavaScript will automatically convert the array into a regular object.

After this automatic conversion, array methods and properties may return undefined or produce incorrect results.

Example:

const person = [];
person[“firstName”] = “John”;
person[“lastName”] = “Doe”;
person[“age”] = 46;
person.length;      // person.length will return 0
person[0];          // person[0] will return undefined

Ending Definitions with a Comma

Trailing commas in object and array definitions are allowed in ECMAScript 5.

Object Example:

person = {firstName:“John”, lastName:“Doe”, age:46,}

Array Example:

points = [40100152510,];

JSON:

person = {“firstName”:“John”“lastName”:“Doe”“age”:46}

JSON:

points = [40100152510];