JavaScript Arrays
- ★ JavaScript array is a special variable, which can hold more than one value at a time.
- ★ An array can hold many values under a single name, and you can access the values by referring to an
index number.
- ★ In JavaScript, arrays always use numbered indexes.
- ★ You can create an array using square brackets []:
let cars=["BMW", 'Volvo', "Saab"];
★ or using the Array constructor:
let cars= new Array("BMW", 'Volvo', "Saab");
- ★ The two examples above do exactly the same.
- ★ For simplicity, readability and execution speed, use the first one.
Access the Elements of an Array
- ★ You refer to an array element by referring to the index number.
- ★ This statement accesses the value of the first element in cars:
let car_name = cars[0];
Array Properties and Methods
- ★ The length property of an array returns the length of an array (the
number of array elements).
- ★ The sort() method sorts an array alphabetically.
By default, .sort() sorts elements as strings in ascending order.
let cars = ["Toyota", "Honda", "Ford", "BMW"];
//The length property returns the number of elements
let carLength = cars.length;
// the sort() method sorts the array alphabetically (A -> Z)
let carsSort = cars.sort();
console.log(carsSort);
- ★ The pop() method removes (and returns) the last element from an array:
let cars=["BMW", "Volvo", "Saab"];
cars.pop();
★ The push() method adds a new element to an array (at the end):
let cars=["BMW", "Volvo", "Saab"];
cars.push("Honda");
★ The unshift() method adds a new element to an array (at the beginning):
let cars=["BMW", "Volvo", "Saab"];
cars.unshift("Nissan");
★ The shift() method removes (and returns) the first element from an array:
let cars=["BMW", "Volvo", "Saab"];
cars.shift();
With JavaScript, the full array can be accessed by referring to the array name:
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
- ★ Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
- ★ But, JavaScript arrays are best described as arrays.
- ★ Arrays use numbers to access its "elements".
- ★ Objects use names to access its "members".
How to Correctly Identify an Array?
Since
typeof isn't reliable for detecting arrays,
JavaScript provides better ways to check if a variable is an array:
Array.isArray()
console.log(Array.isArray(cars)); // Output: true
Looping Through an Array in JavaScript
There are several ways to iterate over an array in JavaScript.
Let’s go over the most commonly used methods.
- ★ Using forEach() (Best for Simple Iteration)
let fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach((fruit) => {
console.log(fruit);
});
- ♣fruits.forEach(...) Calls the forEach() method on the fruits array.
- ♣(fruit) => { ... } Defines an arrow function that runs for each element in fruits.
- ♣fruit represents the current element from the fruits array in each iteration.
★ Using for Loop (Classic Loop)
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
★ Using for...of Loop (Best for Simplicity)
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
while and do...while loops can also be used for iterating through arrays in JavaScript.
Dynamically Generating and Displaying a List Using JavaScript:
Instead of being pre-written in the HTML file, the list is inserted into the <p> element (id="demo")
dynamically using JavaScript.
<p id="demo"></p>
<script>
let 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>";
document.getElementById("demo").innerHTML = text;
</script>
Accessing Index in forEach()
- ★ The forEach() method provides an optional second parameter that
represents the index of the current element in the array.
- ★ Syntax:
array.forEach((element, index) => {
// Code using element and index
});
//element -> The current value in the array.
//index -> The index of the current element (starting from 0).
★ Example 1: Displaying Index and Value
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach((fruit, index) => {
console.log(`Index ${index}: ${fruit}`);
});
★ Example 3: Adding Index to an HTML List
let colors = ["Red", "Green", "Blue"];
let text = "<ul>";
colors.forEach((color, index) => {
text += `<li>Color ${index + 1}: ${color}</li>`;
});
text += "</ul>";
document.getElementById("demo").innerHTML = text;
★ Backticks (``) define a template literal, which allows string interpolation and multiline strings.
★ Uses backticks (``) instead of single (') or double (") quotes.
★ ${name}: String interpolation dynamically inserts the value of the name variable into a string within a template literal.
JavaScript Objects
In JavaScript, an
object is a collection of
key-value pairs.
Objects are used to store related data and methods in a structured way.
- ★ Objects are variables too. But objects can contain many values.
- ★ The values are written as name:value pairs (name and value separated
by a colon).
Creating an Object
There are several ways to create an object in JavaScript.
- ★ Using Object Literal (Most Common)
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false
};
console.log(person);
★ Using new Object() Constructor
let car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
car.year = 2022;
console.log(car);
Objects Properties
- ★ The name:values pairs (in JavaScript objects) are called properties.
Property |
Property Value |
brand |
"Toyota" |
model |
"Corolla" |
year |
2022 |
Accessing Object Properties
- ★ You can access object properties in two ways:
//Dot Notation (Recommended)
car.brand;
or
//Bracket Notation (Useful for Dynamic Keys)
car["brand"]
Adding, Modifying, and Deleting Properties
person.email = "john@example.com";
console.log(person.email); // Output: john@example.com
★ Modifying an Existing Property
person.age = 35;
console.log(person.age); // Output: 35
★ Deleting a Property
delete person.isStudent;
console.log(person.isStudent); // Output: undefined
Object Methods
An object can have methods, which are functions stored as properties.
- ★ Objects can also have methods.
- ★ Methods are actions that can be performed on objects.
- ★ Methods are stored in properties as function definitions.
- ★ Example: Basic Object Method
let car = {
brand: "Toyota",
model: "Corolla",
year: 2022,
// Method inside the object
getCarInfo: function() {
return "Car: " + this.brand + " " + this.model + ", Year: " + this.year;
}
};
console.log(car.getCarInfo());
// Output: Car: Toyota Corolla, Year: 2022
★ Example: Adding a Method to an Existing Object
let person = {
name: "Alice",
age: 25
};
// Adding a method after object creation
person.greet = function() {
return "Hello, my name is " + this.name;
};
console.log(person.greet());
// Output: Hello, my name is Alice
The keyword "this"
- ★ In JavaScript, the this keyword refers to an object.
- ★ In the example above, this refers to the car object.
- ★ The keyword this acts as a placeholder.
- ★ It will refer to whichever object called that method when the method is actually used.
Using an Object Constructor
- ★ The examples above are limited in many situations. They only create a single object.
- ★ Sometimes we like to have an “object type” that can be used to create many objects of one type.
- ★ The standard way to create an “object type” is to use an object constructor function.
- ★ The following function car is an object constructor, Once you have an object constructor, you can
create new objects
of the same type.
- ★ A constructor function in JavaScript is just a regular function, but by convention,
it starts with a capital letter to distinguish it from normal functions.
function Person(name, age) {
this.name = name;
this.age = age;
}
// Creating objects using the constructor
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
console.log(person1.name); // Output: Alice
console.log(person2.age); // Output: 30
Adding Methods to a Constructor
To add methods to all objects created with a constructor, define them using the
prototype.
In JavaScript, a
prototype is a built-in
mechanism for inheritance.
It allows objects to
inherit properties and methods from other objects,
making JavaScript
prototype-based rather than class-based.
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding method to the prototype (shared by all instances)
Person.prototype.greet = function() {
return "Hello, my name is " + this.name;
};
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
console.log(person1.greet()); // Output: Hello, my name is Alice
console.log(person2.greet()); // Output: Hello, my name is Bob
Prototype Method vs. Instance Method
Prototype Method |
Instance Method |
function Person(name, age) {
this.name = name;
this.age = age; }
// ✅ `greet()` is stored in the prototype and shared by all instances
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
console.log(person1.greet()); // Output: Hello, my name is Alice
console.log(person2.greet()); // Output: Hello, my name is Bob
|
function Person(name, age) {
this.name = name;
this.age = age;
// ❌ This method is created separately for every object
this.greet = function() {
return `Hello, my name is ${this.name}`;
};}
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
console.log(person1.greet()); // Output: Hello, my name is Alice
console.log(person2.greet()); // Output: Hello, my name is Bob
|
Now greet() is stored only once in Person.prototype, and
all instances of Person share the same method instead of each object having its own copy. |
Every time new Person(...) is called, a new copy of greet() is created,
which wastes memory. |
Array of Objects
An Array of Objects is an array where
each element is an object.
This is useful when you need to store multiple objects with similar properties in a structured format.
Creating an Array of Objects
let people = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "Los Angeles" },
{ name: "Charlie", age: 35, city: "Chicago" }
];
console.log(people);
Accessing Objects in an Array
You can access objects using
indexing (array[index])
and then access properties with
dot notation (.) or
bracket notation ([]).
console.log(people[0]); // Output: { name: "Alice", age: 25, city: "New York" }
console.log(people[1].name); // Output: Bob
console.log(people[2]["city"]); // Output: Chicago
Looping Through an Array of Objects
To access all objects, you can use forEach(), for...of, or a for loop.
- ★ Using forEach() (Recommended)
people.forEach(person => {
console.log(`${person.name} is ${person.age} years old and lives in ${person.city}.`);
});
★ Using for...of Loop
for (let person of people) {
console.log(person.name);
}
★ Using for Loop with Index
for (let i = 0; i < people.length; i++) {
console.log(people[i].city);
}
Creating an Array of Objects Using a Constructor
function Car(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
let cars = [
new Car("Toyota", "Corolla", 2022),
new Car("Honda", "Fit", "2010"),
new Car("Honda", "Civic", 2023)
];
console.log(cars[0].model); // Output: "Corolla"
Sorting an Array of Objects in JavaScript
The sort() method is used to sort elements in an array. By default, it sorts as strings in ascending order.
To sort numbers, and objects, you need a custom compare function.
Sorting Numbers (Using a Compare Function)
- ★ Ascending Order (Smallest to Largest)
let numbers = [245, 28, 139];
numbers.sort((a, b) => a - b);
console.log(numbers);
★ Descending Order (Largest to Smallest)
let numbers = [245, 28, 139];
numbers.sort((a, b) => b - a);
console.log(numbers);
Sorting an Array of Objects
- ★ Sort by a String Property
// Sort by name alphabetically in Ascending Order (A -> Z)
let people = [
{ name: "Charlie", age: 35 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);
// Sort by name alphabetically in Descending Order (Z -> A)
let people = [
{ name: "Charlie", age: 35 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
people.sort((a, b) => b.name.localeCompare(a.name));
console.log(people);
★ Sort by a Numeric Property
// Sort by age (Ascending)
people.sort((a, b) => a.age - b.age);
console.log(people);
//Sort by age (Descending)
people.sort((a, b) => b.age - a.age);
console.log(people);
★ Sorting by Multiple Criteria
people.sort((a, b) => {
if (a.age === b.age) {
return a.name.localeCompare(b.name);
}
return a.age - b.age;
});
//Sorts by age, and if two people have the same age, it sorts by name.
★ Sorting Dates
let events = [
{ title: "Event A", date: "2024-06-10" },
{ title: "Event B", date: "2023-12-05" },
{ title: "Event C", date: "2025-01-15" }
];
// Sort by date (Oldest to Newest)
events.sort((a, b) => new Date(a.date) - new Date(b.date));
console.log(events);
// Sort by date (Newest to Oldest)
events.sort((a, b) => new Date(b.date) - new Date(a.date));
console.log(events);
Sorting Without Modifying the Original Array
Since sort()
modifies the original array,
use
slice() or spread operator(
[...]) to create a sorted copy.
let numbers = [100, 20, 3];
// Create a sorted copy using spread operator [...array]
let sortedNumbers = [...numbers].sort((a, b) => a - b);
console.log(numbers); // Original: [100, 20, 3]
console.log(sortedNumbers); // Sorted Copy: [3, 20, 100]
let numbers = [100, 20, 3];
// Create a sorted copy using slice()
let sortedNumbers = numbers.slice().sort((a, b) => a - b);
console.log(numbers); // Original: [100, 20, 3]
console.log(sortedNumbers); // Sorted Copy: [3, 20, 100]
Reverse an Sorted Array
let sortedNumbers = [1, 3, 20, 100];
sortedNumbers.reverse();
console.log(sortedNumbers);
Summary of sort() Usage
Sorting Type |
Compare Function |
Alphabetical (Strings - Ascending) |
array.sort(); |
Alphabetical (Strings - Descending) |
array.sort((a, b) => b.localeCompare(a)); |
Numbers (Ascending) |
array.sort((a, b) => a - b); |
Numbers (Descending) |
array.sort((a, b) => b - a); |
Objects (By String Property - Ascending) |
array.sort((a, b) => a.name.localeCompare(b.name)); |
Objects (By String Property - Descending) |
array.sort((a, b) => b.name.localeCompare(a.name)); |
Objects (By Numeric Property - Ascending) |
array.sort((a, b) => a.age - b.age); |
Objects (By Numeric Property - Descending) |
array.sort((a, b) => b.age - a.age); |
Sorting Dates (Oldest to Newest) |
array.sort((a, b) => new Date(a.date) - new Date(b.date)); |
Sorting Dates (Newest to Oldest) |
array.sort((a, b) => new Date(b.date) - new Date(a.date)); |
Sorting by Multiple Criteria (Primary: Age, Secondary: Name) |
array.sort((a, b) => a.age === b.age ? a.name.localeCompare(b.name) : a.age - b.age); |
Breakdown of Syntax
array.sort((a, b) => a - b);
- ★(a, b) => a - b is an arrow function that
serves as the compare function for sorting.
- ♣ a and b -> Represent two elements being compared.
- ♣ a - b -> Determines the order of sorting:
- If a - b is negative (a < b), a comes before b (correct order).
- If a - b is positive (a > b), b comes before a (swap places).
- If a - b is 0, they remain in the same order.
JavaScript Comments
- ★ JavaScript comments can be used to explain JavaScript code, and to make it more readable.
- ★ JavaScript comments can also be used to prevent execution, when testing alternative code.
Single Line Comments
- ★ Single line comments start with //.
Multi-line Comments
- ★ Multi-line comments start with /* and end with
*/
.
Reference