JavaScript Arrays

Access the Elements of an Array

				let car_name = cars[0];
			

Array Properties and Methods

			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);
		

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>
		

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. 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()

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.

Creating an Object

There are several ways to create an object in JavaScript.

Objects Properties

Property Property Value
brand "Toyota"
model "Corolla"
year 2022

Accessing Object Properties

	
			//Dot Notation (Recommended)
			car.brand;
			
			or
			//Bracket Notation (Useful for Dynamic Keys)
			car["brand"]
		

Adding, Modifying, and Deleting Properties

Object Methods

An object can have methods, which are functions stored as properties.

The keyword "this"

Using an Object Constructor

		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.

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)

Sorting an Array of Objects

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);

JavaScript Comments

Single Line Comments

Multi-line Comments



Reference