Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Adding Array Elements

The simplest method to append a new element to an array is by employing the push() method.

Example

const fruits = [“Banana”“Orange”“Apple”];
fruits.push(“Lemon”);  // Adds a new element (Lemon) to fruits

An alternative approach to adding a new element to an array involves utilizing the length property.

Example

const fruits = [“Banana”“Orange”“Apple”];
fruits[fruits.length] = “Lemon”;  // Adds “Lemon” to fruits

Caution!

Adding elements with high indexes may result in creating undefined “holes” within an array.

Example

const fruits = [“Banana”“Orange”“Apple”];
fruits[6] = “Lemon”;  // Creates undefined “holes” in fruits

Associative Arrays

Numerous programming languages accommodate arrays with named indexes, known as associative arrays or hashes.

Contrarily, JavaScript does not support arrays with named indexes; instead, arrays exclusively employ numbered indexes.

Example

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

Caution!

When named indexes are utilized, JavaScript will reinterpret the array as an object. Consequently, certain array methods and properties may yield inaccurate outcomes.

Example

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

The Difference Between Arrays and Objects

In JavaScript, arrays utilize numbered indexes, whereas objects employ named indexes.

Arrays are a distinct type of objects distinguished by their utilization of numbered indexes.

When to Use Arrays. When to use Objects.

  • JavaScript does not natively support associative arrays.
  • Objects are preferable when the element names are strings (text), while arrays are better suited for element names represented as numbers.