JavaScript Arrays Tutorials – Explained with Examples for Beginners

While learning any programming language, we come across the learning of Arrays. Arrays come in helpful when there is a need to store several different values in a single variable. Arrays application is seen at many places, like implementing the matrices, data structures or storing data in tabular form.

The concept of arrays came from the arrangement of objects in real life. The way we arrange objects in real life, we can arrange the data in programming. So this post is all about learning the core and basic concepts of Arrays in JavaScript. Let’s dive in and have a clear understanding of an array, how to create it, and use it to assign, access, and change values.

What is an Array?

An array is a variable type in any programming language used to store multiple values simultaneously. Arrays store the data in the form of segments, also known as elements of the Array, so in simple words, an array is a collection of elements.

We usually use them to store the same type of values or the list of items in one place/variable like the name of animals [“lion,” “bear,” “monkey”] or list of students [“John,” “Bob,” “Ivan”].

However, we can store multiple data types in arrays, like strings, integers, arrays, or even functions.

The array types concerning implementation are divided into four types:

  • Homogeneous arrays
  • Heterogeneous arrays
  • Multidimensional arrays
  • Jagged arrays

Let’s have a short introduction of each type.

Homogeneous Array:

The Array in which the elements are of the same data type is known as a homogeneous array. For example, string, integers, or bool values.

var stringArr = ["John", "Bob", "Ivan"];
var intArr = [23, 45, 67];

Heterogenous Array

The Array in which values of multiple data types are stored is known as heterogeneous Array. For example:

var student = ["John", 25, "male"]

Multidimensional Array:

The array which contains further arrays as elements in it is known as a multidimensional array. For example, list of students:

var student = [["John", 25, "male"], ["Steve", 21, "male"], ["Angela", 22, "female"]]

Jagged Array:

Jagged is almost the same as a multidimensional array but with a subtle difference in the number of elements in the sub-arrays within an array. The multidimensional Array in which the additional arrays datasets are not uniform.

var student = [["John"], ["Steve", 21, "male"], ["Angela", "female"]]

Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:

  • use the F12 key in Chrome and other chromium-based browsers.
  • use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
  • use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).

How to create an array?

Since JavaScript is a scripting language, we do not first have to declare the type and assign some values to a variable. We can directly write the variable’s name without mentioning the variable data type and assign values to it.

For example:

var languages = ["javascript", "python", "java"];

How to assign values to an array?

Although we can assign values to an array while creating the Array, there is another way to assign values is by assigning values to specific indexes. The location where an item is present in an array is known as its index.

For example:

var languages = [];
languages[0] = "JavaScript";
languages[1] = "Python";

Note: In arrays, index numbers start from “0”(zero):

How to change the value of an array element?

The value of an element present in an Array can be changed the same way we can assign its values.

For example, if we want to change the value of the first index of the “languages” array, the statement would go like this:

languages[0] = "TypeScript";

Built-in Array Properties and Methods:

The real perk of javascript is its built-in properties and methods for arrays. The most common array properties and methods present in JavaScript are:

array.length property:

The “array.length” property can be used to get the number of items/elements present in an array. For example:

var languages = ["javascript", "python", "java"];
console.log(languages.length);

array.sort() method:

This Array.sort() method sorts the elements present in an array in ascending order.

Suppose, we have an array of three programming languages:

var languages = ["javascript", "python", "java"];

and we want to sort them out in alphabetical order so that the sort function will go like this:

let sortedLang = languages.sort();
console.log(sortedLang);

In the output, you can see the Array is sorted as we desired:

How to access the elements/items of an Array?

Array elements can be accessed by mentioning the index number.

For example, we want to access the second element of an array; the statement would go like this:

let secondLanguage = languages[1];

Note: Array’s index number starts from zero“0”:

How to access the first element/item of an array?

Since Array indexes start from “0,” so we can access the first element of an array by mentioning “0” in the square brackets as shown below:

let firstLanguage = languages[0];

How to access the last element/item of an array?

To get the last item of an array, the “array.length” property comes in help. We can access the last element present in an array by mentioning “array.length -1” in the square brackets as shown below:

let lastLanguage = languages[languages.length - 1];

How to loop through an Array?

To get all the elements present in an array, the best way is to loop through an array. The most convenient and efficient ways are to use:

  • For loop
  • array’s foreach method

For loop:

To fetch all the elements using a for loop is the easiest way. Simply execute the code given below to loop through the whole Array and fetch all the elements one by one:

var languages = ["javascript", "python", "java"];

for (let i = 0; i < languages.length; i++) {
 const language = languages[i];
 console.log(language);
}

In the above code, you can see that we used languages.length property in the conditional clause of for loop in order to loop through the whole Array without knowing the total number of elements in the Array.

Array’s foreach method:

Javascript also provides the foreach method of the Array to loop through the whole Array. The syntax of using the foreach method is as follows:

var languages = ["javascript", "python", "java"];

languages.forEach(oneLang);

function oneLang(language){
 console.log(language);
}

The above-provided syntax can be shortened using the inline callback function as given below:

languages.forEach((language)=>{
 console.log(language);
})

Associative arrays in JavaScript?

Associative arrays are the arrays that have named indices. JavaScript does not support such arrays. If you do so, javaScript will take it as an object, and the methods and properties of the Array won’t apply to it.

Javascript Arrays are Objects:

Yes, the type of Array in javaScript is Object. That’s why the arrays can hold different types of variables. Arrays can hold objects, functions, and even arrays within an array as an element.

If we use the typeof operator over an array variable:

var languages = ["javascript", "python", "java"];

console.log(typeof(languages));

It will show that the type of “languages” array variable is an object.

However, there are still some conceptual differences between Arrays and Objects:

Difference between Arrays and Objects:

  • In arrays, the indexes are denoted by numbers.
  • While, in objects, the indexes can be denoted by names(numbers or alphabets).

So, it is better to choose the right variable type at the right place:

  • Use Arrays when you have a large list of items.
  • Use Objects when you need to assign names to the indexes.

Now, the question arises, how to identify whether a variable is an object or Array.

How to identify an Array Variable?

For identifying, either a variable is an array or not, JavaScript provides an Array.isArray() function.

For example:

var languages = ["javascript", "python", "java"];

console.log(Array.isArray(languages));

The above code will return true.

Note: The Array.isArray() function was introduced in ECMAScript 5.

Conclusion

This post contains all the basic and necessary knowledge required for getting started with arrays in JavaScript. We first introduce What arrays are, then we learned how to create, assign, and change the values of an array.

Moreover, we have learned some basic built-in properties and functions of arrays in javaScript to get more interactive with arrays. In the end, we discussed the data type of Array and the difference between Arrays and Objects in detail.



from https://ift.tt/3ALloyQ

Post a Comment

0 Comments