Lets learn Basics of Array using JavaScript

Atul jha
11 min readJul 18, 2023

--

Introduction

Arrays are an essential and powerful data structure that allows us to store and manipulate collections of elements efficiently. Whether you’re a beginner or already familiar with JavaScript, understanding arrays is crucial for building dynamic and interactive web applications. In this blog, we will explore the fundamentals of arrays, learn how to add, remove, and manipulate array elements, find specific values within arrays, sort and join arrays, and iterate over their elements using various methods. Get ready to dive into the world of arrays and unlock their potential in JavaScript programming. Let’s begin our journey into the fascinating realm of arrays!

What are Arrays?

Arrays are a fundamental data structure in JavaScript used to store and organize collections of elements. They provide a convenient way to work with multiple values as a single entity. Arrays can contain any combination of primitive values (such as numbers, strings, booleans) or reference values (such as objects, functions, or other arrays).

Arrays provides various methods and properties that enable us to add, remove, search, and modify elements within the collection. We will understand all these methods in this blog itself.

Declaring and initializing an array:

The most common method of declaring an array is to use square brackets [ ] to enclose a comma-separated list of elements:

let numbers = [1, 2, 3, 4, 5];
let fruits = ['apple', 'banana', 'orange'];
let mixedArray = [1, 'hello', true, null, { name: 'Atul' }];

In the examples above, we declare arrays named numbers, fruits, and mixedArray and initialize them with different elements. Note that arrays can contain elements of different types, allowing for versatility in data representation.

Accessing Array elements:

To access individual elements within an array, we use zero-based indexing. Each element is assigned an index starting from 0 for the first element, 1 for the second element, and so on.

let numbers = [1, 2, 3, 4, 5];

console.log(numbers[0]); // Output: 1
console.log(numbers[2]); // Output: 3
console.log(numbers[4]); // Output: 5

In the example above, we access elements of the numbers array by specifying their respective indices within square brackets.

It’s important to note that JavaScript arrays are dynamic, meaning their size can change dynamically by adding or removing elements. There is no fixed limit to the number of elements an array can hold.

Now lets start learning the concept of manipulating arrays….

JS Array Length:

The length property of arrays in JavaScript provides the number of elements present in an array. It allows you to determine the size or length of an array dynamically. Here's an explanation with an example:

let fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // Output: 3

In the example above, the array fruits contains three elements. By accessing the length property (fruits.length), we obtain the value 3, indicating the number of elements in the array.

The length property is automatically updated whenever elements are added to or removed from the array. It provides a convenient way to check the size of an array dynamically, making it useful for various operations and conditions in your code.

Adding elements in Array:

In JavaScript, there are multiple ways to add elements to an array. Here are a few common methods:

  • push(): The push() method adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array.
let numbers = [1, 2, 3];
numbers.push(4);
numbers.push(5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
  • unshift(): The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It also modifies the original array.
let numbers = [2, 3, 4];
numbers.unshift(0);
numbers.unshift(1);
console.log(numbers); // Output: [0, 1, 2, 3, 4]
  • Specific index array assignment: You can assign values to specific index no. of an array to add elements.
let numbers = [1, 2, 4];
numbers[2] = 3;
console.log(numbers); // Output: [1, 2, 3]

In the examples above, elements are added to the array numbers using the push() method, unshift() method, and direct assignment to an index.

It’s important to note that these methods modify the original array. If you want to create a new array without modifying the original, you can use methods like concat() or the array spread syntax ([...array]) to create a new array with the added elements.

You can refer to this blog to learn about spread operator & Concatenation.

Removing element in Array:

JavaScript provides various techniques to remove elements from an array. Here are a few common methods:

  • pop(): The pop() method removes the last element from an array and returns the removed element. It also modifies the original array.
let numbers = [1, 2, 3, 4];
let removedElement = numbers.pop();
console.log(numbers); // Output: [1, 2, 3]
console.log(removedElement); // Output: 4
  • shift(): The shift() method removes the first element from an array and returns the removed element. It modifies the original array.
let numbers = [1, 2, 3, 4];
let removedElement = numbers.shift();
console.log(numbers); // Output: [2, 3, 4]
console.log(removedElement); // Output: 1
  • Array Assignment: You can assign a new value (undefined) or remove an element by assigning undefined or null to a specific index.
let numbers = [1, 2, 3, 4];
numbers[2] = undefined;
console.log(numbers); // Output: [1, 2, undefined, 4]

In the examples above, elements are removed from the array numbers using the pop() method, shift() method, and by assigning undefined to an index.

Similar to adding elements, these methods modify the original array. If you want to create a new array without the removed elements, you can use methods like slice() or the array filter method (filter()) to create a new array with the desired elements.

Emptying an Array:

Emptying an array refers to the process of removing all elements from the array. There are several approaches to achieve this:

  • Reassigning an Empty Array: You can empty an array by assigning it an empty array literal ([]), which effectively replaces the existing array with a new empty array.
let numbers = [1, 2, 3, 4];
numbers = [];
console.log(numbers); // Output: []

// Don't declare the number variable using const.
// As once the values are assigned it can be modified

In the above example, the array numbers is emptied by assigning it an empty array.

  • Using the Length Property: Another approach is to set the length property of the array to 0. This method effectively truncates the array, removing all elements beyond the new length.
let numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers); // Output: []

In this example, setting numbers.length to 0 results in an empty array.

Both methods effectively empty the array, but it’s important to note that they differ in how they handle the original array reference. Reassigning an empty array creates a new array instance, while modifying the length property modifies the original array in place.

Finding Elements in array (Primitives):

When dealing with arrays of primitive values (such as numbers, strings, booleans), JavaScript provides several methods to find specific elements:

  • indexOf(): The indexOf() method returns the first index at which a given element is found in the array. If the element is not found, it returns -1.
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.indexOf(3)); // Output: 2
console.log(numbers.indexOf(6)); // Output: -1 (element not found)

In the example above, indexOf(3) returns 2, indicating that the element 3 is found at index 2 in the array.

  • includes(): The includes() method determines whether an array contains a specific element and returns a boolean value (true or false).
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // Output: true
console.log(numbers.includes(6)); // Output: false

In this example, includes(3) returns true since the element 3 is present in the array.

  • find(): The find() method returns the first element in the array that satisfies a provided testing function. If no element satisfies the condition, it returns undefined.
let numbers = [1, 2, 3, 4, 5];
let foundNumber = numbers.find((element) => element > 3);
console.log(foundNumber); // Output: 4

In the above example, find() returns 4 as the first element greater than 3 in the array.

These methods provide ways to search for specific primitive values in an array, enabling you to locate and perform further operations on the found elements.

Finding Elements in array (Reference Types):

When dealing with arrays of reference types (such as objects, functions, or arrays themselves), additional methods can be used to find elements:

  • find(): The find() method can also be used with reference types. It returns the first element in the array that satisfies a provided testing function.
let employees = [
{ id: 1, name: 'Raj' },
{ id: 2, name: 'Kanha' },
{ id: 3, name: 'Vishnu' },
];

let foundEmployee = employees.find((employee) => employee.id === 2);
console.log(foundEmployee); // Output: { id: 2, name: 'Kanha' }

In this example, find() returns the employee object with an id of 2.

  • filter(): The filter() method creates a new array with all elements that pass a provided testing function.
let employees = [
{ id: 1, name: 'Raj' },
{ id: 2, name: 'Kanha' },
{ id: 3, name: 'Vishnu' },
];

let filteredEmployees = employees.filter((employee) => employee.name.startsWith('R'));
console.log(filteredEmployees); // Output: [{ id: 1, name: 'Raj' }

In this example, filter() returns a new array containing the employee objects with names starting with 'R'.

Custom comparison functions can be used with both find() and filter() to define specific criteria for finding elements within the array.

These methods allow you to search arrays of reference types based on specific conditions, making it easier to locate and work with the desired elements.

Sorting Arrays:

Sorting arrays in JavaScript involves arranging the elements of an array in a specific order.

  • Manual Swap Sorting Technique: The manual swap sorting technique, also known as the bubble sort algorithm, is a simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the array is sorted.

Here’s an example of how the bubble sort algorithm can be implemented:

function bubbleSort(arr) {
let len = arr.length;
let swapped;

do {
swapped = false;
for (let i = 0; i < len - 1; i++) {
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped);

return arr;
}

let numbers = [5, 3, 8, 1, 2];
console.log(bubbleSort(numbers)); // Output: [1, 2, 3, 5, 8]

In the example above, the bubbleSort() function implements the manual swap sorting technique on the numbers array. The algorithm repeatedly compares adjacent elements and swaps them if necessary until the array is sorted in ascending order.

  • Using the sort() method: JavaScript arrays provide a built-in sort() method, which sorts the elements of an array in place and returns the sorted array. By default, the sort() method sorts elements as strings based on their Unicode code points. However, for numerical or custom sorting, you can provide a custom comparison function as a parameter.
let numbers = [5, 3, 8, 1, 2];
numbers.sort();
console.log(numbers); // Output: [1, 2, 3, 5, 8]

In the example above, the sort() method is used to sort the numbers array. Since the elements are numbers, the default string-based comparison results in the array being sorted correctly.

Joining Arrays:

The join() method in JavaScript allows you to join the elements of an array into a single string. You can specify a separator that will be inserted between the elements in the resulting string.

Here’s an example of using the join() method:

let fruits = ['apple', 'banana', 'orange'];
let joinedString = fruits.join(', ');
console.log(joinedString); // Output: "apple, banana, orange"

In the example above, the join(', ') call joins the elements of the fruits array into a single string with a comma and space as the separator.

By default, if no separator is provided to the join() method, it uses a comma as the separator. However, you can customize the separator by passing it as an argument.

Iterating array:

Array iteration methods allow you to iterate over each element in an array and perform certain actions or transformations. Here are some commonly used array iteration methods:

  • forEach(): The forEach() method executes a provided function once for each element in the array.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number * 2);
});
// Output: 2, 4, 6, 8, 10

In this example, the forEach() method is used to iterate over each element in the numbers array and log its double to the console.

  • map(): The map() method creates a new array by calling a provided function on each element in the array.
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map((number) => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this example, the map() method transforms each element in the numbers array by multiplying it by 2 and creates a new array (doubledNumbers) with the transformed values.

  • filter(): The filter() method creates a new array with all elements that pass a provided test implemented by a provided function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

In this example, the filter() method filters out the odd numbers from the numbers array and creates a new array (evenNumbers) containing only the even numbers.

  • reduce(): The reduce() method applies a provided function to reduce the array to a single value.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentNumber) => accumulator + currentNumber, 0);
console.log(sum); // Output: 15

In this example, the reduce() method calculates the sum of all the numbers in the numbers array by continuously adding each number to the accumulator (sum) starting from an initial value of 0.

Example time:

As an example incorporating many of these array concepts, let’s consider a minor project. We will be developing a simple task management application where users can create, update, and delete tasks. We will utilize arrays to store and manage the task data. Here’s a simplified code snippet & live working project. (You can apply more style & publish it on your github as an minor project😬)

In the above project, we have created an HTML To-Do form where users can enter tasks. On clicking the “Add Task” button, the addTask() function is called, which adds the task to the tasks array. The renderTasks() function iterates over the array using forEach() and dynamically generates a list of tasks in the HTML.

This minor project showcases concepts such as adding elements to an array (push()), rendering array elements (forEach()), and utilizing arrays for managing dynamic data.

Conclusion:

In this blog of JavaScript arrays, we have covered various topics related to their usage and manipulation. We began with an introduction to arrays, understanding their purpose as a fundamental data structure for organizing and managing collections of elements. We learned how to declare and initialize arrays using different methods.

Moving forward, we discussed the length property of arrays, which provides the number of elements present in an array. We explored techniques for adding and removing elements from arrays using methods like push(), pop(), unshift(), shift(), and array assignment.

We also delved into emptying an array through different approaches, including reassigning an empty array and utilizing the length property. We explored finding elements in arrays, both with primitive values and reference types, using methods like indexOf(), includes(), find(), and filter().

Sorting arrays was another important aspect we covered, including the manual swap sorting technique and utilizing the sort() method with custom comparison functions. Additionally, we explored joining array elements into a single string using the join() method.

Lastly, we introduced array iteration methods like forEach(), map(), filter(), and reduce(), which enable us to iterate over array elements and perform various actions or transformations.

To conclude, understanding JavaScript arrays is essential for effective data management and manipulation in web development. By mastering these array concepts, you can build powerful applications that efficiently handle collections of data.

If you enjoyed what you read & found it insightful, please consider supporting me here Your support is greatly appreciated!

If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!

--

--

Atul jha

I am a web enthusiast who is trying to pave his path towards being an awesome developer by exploring, learning & sharing the knowledge.