This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

JavaScript Array


In JavaScript, an array is a data structure that can store a collection of elements of any data type, including numbers, strings, objects, and even other arrays

Advantage of Array

Arrays offer several advantages in programming

  1. Efficient Storage and Access - Arrays provide a contiguous block of memory to store elements, which makes accessing elements by index very efficient. Retrieving an element from an array using its index takes constant time, O(1), which means it is very fast even for very large arrays.
  2. Versatility - Arrays can store elements of any data type, including numbers, strings, objects, and even other arrays. This makes them a flexible and versatile data structure that can be used in a wide range of applications.
  3. Easy to Manipulate - Arrays have built-in methods that make it easy to manipulate them, such as adding or removing elements, sorting, filtering, and more. These methods make it easy to perform common operations on arrays without having to write custom code.
  4. Simple Syntax - Creating and accessing arrays in JavaScript is very simple and intuitive, which makes it easy for beginners to learn and use. The syntax for creating an array is straightforward, and accessing elements by index is as simple as using square brackets.
  5. Familiarity - Arrays are a common data structure in programming, and most programmers are familiar with how they work. This makes it easy to collaborate with other programmers and share code that uses arrays.

Disadvantage of Array

While arrays have many advantages, they also have some disadvantages:

  1. Fixed Size - In some programming languages, arrays have a fixed size, which means that you need to specify the size of the array when you create it. If you need to add or remove elements from the array, you may need to create a new array with a larger or smaller size, which can be inefficient and time-consuming.
  2. Linear Search - If you need to search for an element in an array, you may need to perform a linear search, which means that you need to iterate over the elements in the array until you find the element you are looking for. This can be slow for large arrays, and it can also be difficult to implement efficiently.
  3. Inefficient Insertions and Deletions - If you need to insert or delete an element from the middle of an array, you may need to shift all the elements after the insertion or deletion point, which can be inefficient and time-consuming.
  4. Wasted Memory - If you create an array with a fixed size that is larger than the number of elements that you actually need, you may be wasting memory. This can be a problem if you are working with large arrays or if memory is limited.
  5. Not Suitable for Key-Value Pairs - While arrays are useful for storing collections of elements, they are not suitable for storing key-value pairs. For this purpose, you may need to use a different data structure, such as an object or a map.

Overall, while arrays are a powerful and versatile data structure, they have some limitations and drawbacks that you need to be aware of. Depending on your specific use case, you may need to choose a different data structure that better suits your needs.

Real World Example of Array

Music Playlist: A music player application can use an array to store the songs in a user's playlist. Each song can be represented as an object with properties such as name, artist, album, duration, etc. The array can be used to store all the songs in the playlist, and it can be manipulated using array methods to add or remove songs.

Here's an example of how to declare an array in JavaScript:

 let myArray = [1, 2, 3, 'four', {name: 'John'}, true];

In this example, myArray is an array that contains six elements of different data types. You can access elements in an array using their index. Array indices start at 0, so the first element in an array has an index of 0, the second element has an index of 1, and so on.

Here's an example:

let myArray = ['apple', 'banana', 'cherry'];

console.log(myArray[0]); 
// Output: 'apple' console.log(myArray[1]);
// Output: 'banana' console.log(myArray[2]);
 // Output: 'cherry'

You can also change the value of an array element by assigning a new value to its index:

 let myArray = ['apple', 'banana', 'cherry'];


myArray[1] = 'orange'; console.log(myArray);
// Output: ['apple', 'orange', 'cherry']

Arrays in JavaScript also have many built-in methods, such as push(), pop(), shift(), unshift(), slice(), splice(), concat(), join(), reverse(), sort(), and more, that you can use to manipulate the array.

Creating an Array in JavaScript

The syntax for creating an array in JavaScript is as follows:

let myArray = [element1, element2, ..., elementN];

In this syntax, myArray is the name of the array variable, and element1, element2, ..., elementN are the elements in the array. Each element can be of any data type, including numbers, strings, objects, and even other arrays.

Here's an example of how to create an array of numbers:

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

Here's an example of how to create an array of strings:

let myArray = ['apple', 'banana', 'cherry'];

Here's an example of how to create an array of objects:

let myArray = [
{name: 'John', age: 30},
{name: 'Jane', age: 25},
{name: 'Bob', age: 40}
];

You can also create an empty array and add elements to it later using array methods:

let myArray = [];
myArray.push('apple');
myArray.push('banana');
myArray.push('cherry');

In this example, myArray is initially an empty array, and the push() method is used to add elements to it.

1. Accessing the Elements of an Array

You can access the elements of an array in JavaScript using the index of the element. The index of the first element in an array is 0, the index of the second element is 1, and so on.

Here's an example.

let myArray = ['apple', 'banana', 'cherry'];
console.log(myArray[0]); // Output: 'apple'
console.log(myArray[1]); // Output: 'banana'

console.log(myArray[2]); // Output: 'cherry'

In this example, myArray is an array of three strings. We access the first element of the array using myArray[0], which returns the string 'apple'. We access the second element of the array using myArray[1], which returns the string 'banana', and so on.

You can also use a variable to access an element of an array dynamically.

For example

let myArray = ['apple', 'banana', 'cherry'];
let index = 1;

console.log(myArray[index]); // Output: 'banana'

In this example, we declare a variable index and assign it the value 1. We then use this variable to access the second element of the myArray array, which is 'banana'.

If you try to access an element of an array using an index that is out of range, you will get the value undefined. For example:

let myArray = ['apple', 'banana', 'cherry'];
console.log(myArray[3]); // Output: undefined

In this example, we try to access the fourth element of the myArray array using an index of 3, which is out of range. The result is undefined.

2. Getting the Length of an Array

You can get the length of an array in JavaScript using the length property. The length property returns the number of elements in the array.

Here's an example:

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

In this example, myArray is an array of three elements. We use the length property to get the number of elements in the array, which is 3.

You can also use the length property to add or remove elements from an array. For example, if you set the length property to a smaller value than the current number of elements in the array, the elements at the end of the array will be removed. If you set the length property to a larger value than the current number of elements in the array, the new elements will be initialized to undefined.

Here are some examples:

myArray = ['apple', 'banana', 'cherry'];
myArray.length = 2; // Removes the last element
console.log(myArray); // Output: ['apple', 'banana']

myArray.length = 4; // Adds two new elements
console.log(myArray); // Output: ['apple', 'banana', undefined, undefined]

In the first example, we set the length property of myArray to 2, which removes the last element of the array ('cherry'). In the second example, we set the length property of myArray to 4, which adds two new elements to the end of the array, initialized to undefined.

3. Looping Through Array Elements

There are several ways to loop through the elements of an array in JavaScript. Here we will use FOR loop.

For Loop: You can use a for loop to iterate over the elements of an array.

Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}

In this example, we use a for loop to iterate over the elements of the myArray array. The loop variable i starts at 0 and increments by 1 until it reaches the length of the array (3). We use the loop variable to access each element of the array using its index.

4. Push() Method - Adding New Elements to an Array

The push() method is a built-in method of arrays in JavaScript that can be used to add one or more elements to the end of an array. The push() method modifies the original array and returns the new length of the array. Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let newLength = 
myArray.push('date');
console.log(myArray); // Output: ['apple', 'banana', 'cherry', 'date']
console.log(newLength); // Output: 4

In this example, we use the push() method to add the string 'date' to the end of the myArray array. The push() method modifies the original array and returns the new length of the array, which is 4. We use the console.log() method to print the modified array and the new length of the array to the console.

5. Pop() Method - Removing Elements from an Array

The pop() method is a built-in method of arrays in JavaScript that can be used to remove the last element from an array. The pop() method modifies the original array and returns the removed element. Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let removedElement = myArray.pop();
console.log(myArray); // Output: ['apple', 'banana'] console.log(removedElement); // Output: 'cherry'

In this example, we use the pop() method to remove the last element ('cherry') from the myArray array. The pop() method modifies the original array and returns the removed element, which is 'cherry'. We use the console.log() method to print the modified array and the removed element to the console.

You can also use the pop() method to remove multiple elements from an array at once. Here's an example:

let myArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
myArray.pop();
myArray.pop();
console.log(myArray); // Output: ['apple', 'banana', 'cherry']

In this example, we use the pop() method twice to remove the last two elements ('date' and 'elderberry') from the myArray array. The pop() method modifies the original array and returns the removed element, but we don't assign the returned values to any variables. We use the console.log() method to print the modified array to the console.

The pop() method is a convenient way to remove elements from the end of an array in JavaScript. It can be useful when you need to remove data from an existing array, or when you need to process an array iteratively and remove elements as you go.

6. Spice() Method - Adding or Removing Elements

The splice() method is a built-in method of arrays in JavaScript that can be used to add or remove elements from an array. The splice() method modifies the original array and returns an array of the removed elements, if any. Here's an example:

let myArray = ['apple', 'banana', 'cherry', 'date'];
myArray.splice(2, 1, 
'elderberry', 'fig');
console.log(myArray); // Output: ['apple', 'banana', 'elderberry', 'fig', 'date']

In this example, we use the splice() method to remove one element at index 2 ('cherry') from the myArray array, and then add the strings 'elderberry' and 'fig' at the same index. The first argument to the splice() method specifies the index at which to start adding or removing elements, and the second argument specifies the number of elements to remove. Any additional arguments are added to the array at the specified index. The splice() method modifies the original array and returns an array of the removed elements ('cherry' in this case), but we don't assign the returned value to any variable. We use the console.log() method to print the modified array to the console.

You can also use the splice() method to remove multiple elements from an array at once. Here's an example:

let myArray = ['apple', 'banana', 'cherry', 'date'];
let removedElements = 
myArray.splice(1, 2);
console.log(myArray); // Output: ['apple', 'date']
console.log(removedElements); // Output: ['banana', 'cherry']

In this example, we use the splice() method to remove two elements starting at index 1 ('banana' and 'cherry') from the myArray array. The splice() method modifies the original array and returns an array of the removed elements (['banana', 'cherry'] in this case), which we assign to the removedElements variable. We use the console.log() method to print the modified array and the removed elements to the console.

The splice() method is a powerful way to add or remove elements from an array in JavaScript. It can be useful when you need to modify an existing array in-place, or when you need to manipulate an array in complex ways.

7. Join() Method - Creating a String from an Array

The join() method is a built-in method of arrays in JavaScript that can be used to join all the elements of an array into a single string. The join() method returns a new string that contains all the elements of the array concatenated together with the specified separator.

Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let joinedString = 
myArray.join(', ');
console.log(joinedString); // Output: 'apple, banana, cherry'

In this example, we use the join() method to join all the elements of the myArray array into a single string with a comma and a space (', ') as the separator. The join() method returns a new string that contains all the elements of the array concatenated together with the specified separator ('apple, banana, cherry' in this case), which we assign to the joinedString variable. We use the console.log() method to print the joined string to the console.

You can also use the join() method with an empty string as the separator to concatenate all the elements of an array together without any separator.

Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let joinedString = myArray.join('');
console.log(joinedString); // Output: 'applebananacherry'

In this example, we use the join() method with an empty string ('') as the separator to concatenate all the elements of the myArray array together without any separator. The join() method returns a new string that contains all the elements of the array concatenated together without any separator ('applebananacherry' in this case), which we assign to the joinedString variable. We use the console.log() method to print the joined string to the console.

The join() method is a useful way to convert an array into a string in JavaScript. It can be useful when you need to display the contents of an array in a user interface, or when you need to transmit an array as a string over a network.

8. Slice() Method - Extracting a Portion of an Array

The slice() method is a built-in method of arrays in JavaScript that can be used to extract a portion of an array into a new array, without modifying the original array. The slice() method returns a new array that contains the extracted elements. Here's an example:

let myArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
let newArray = myArray.slice(1, 4);
console.log(newArray); // Output: ['banana', 'cherry', 'date']
console.log(myArray); // Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']

In this example, we use the slice() method to extract a portion of the myArray array into a new array. The first argument to the slice() method specifies the starting index of the extraction (inclusive), and the second argument specifies the ending index of the extraction (exclusive). The slice() method returns a new array that contains the extracted elements (['banana', 'cherry', 'date'] in this case), which we assign to the newArray variable. The original myArray array is not modified. We use the console.log() method to print the new array and the original array to the console.

9. Shift() Method - Remove the first element from an array

The shift() method is a built-in method of arrays in JavaScript that can be used to remove the first element from an array. The shift() method modifies the original array and returns the removed element. Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let removedElement = myArray.shift();
console.log(myArray); // Output: ['banana', 'cherry']
console.log(removedElement); // Output: 'apple'

In this example, we use the shift() method to remove the first element ('apple') from the myArray array. The shift() method modifies the original array and returns the removed element, which is 'apple'. We use the console.log() method to print the modified array and the removed element to the console.

10. Reverse() Method - Reverse the order of the elements in an array

The reverse() method is a built-in method of arrays in JavaScript that can be used to reverse the order of the elements in an array. The reverse() method modifies the original array and returns the reversed array. Here's an example:

let myArray = ['apple', 'banana', 'cherry'];
let reversedArray = myArray.reverse();
console.log(reversedArray); // Output: ['cherry', 'banana', 'apple']
console.log(myArray); // Output: ['cherry', 'banana', 'apple']

In this example, we use the reverse() method to reverse the order of the elements in the myArray array. The reverse() method modifies the original array and returns the reversed array (['cherry', 'banana', 'apple'] in this case), which we assign to the reversedArray variable. The original myArray array is also reversed. We use the console.log() method to print the reversed array and the original array to the console.

JavaScript vs Other programming Array

JavaScript arrays offer several advantages over arrays in other programming languages:

  1. Dynamic Size- JavaScript arrays are dynamic in size, which means that you don't need to specify the size of the array when you create it. You can add or remove elements from the array as needed, which makes it easy to work with data that changes in size.
  2. Supports Heterogeneous Data Types- JavaScript arrays can store elements of different data types in the same array. This makes it easy to work with data that has different types of values, such as an array of objects or an array of mixed data types.
  3. Built-in Methods- JavaScript arrays have built-in methods that make it easy to manipulate them, such as push, pop, shift, unshift, slice, splice, and more. These methods make it easy to perform common operations on arrays without having to write custom code.
  4. Functional Programming- JavaScript arrays support functional programming concepts, such as map, reduce, and filter. These methods allow you to manipulate arrays in a declarative and concise way, which can make your code more readable and maintainable.
  5. Easy to Work with in the Browser- JavaScript arrays are easy to work with in the browser, which makes them a popular choice for web development. You can use JavaScript arrays to manipulate the DOM, handle user input, and create dynamic web applications.

Overall, JavaScript arrays offer many advantages over arrays in other programming languages. They are dynamic in size, support heterogeneous data types, have built-in methods, support functional programming, and are easy to work with in the browser


Prev Next