Saturday, March 30, 2024

What are Arrays in Javascript?

An array is a special variable, which can hold more than one value. Arrays are a special kind of objects, with numbered indexes.

What is the difference between Arrays and Objects?

In JavaScript, arrays use numbered indexes.  

In JavaScript, objects use named indexes.

How to create an array?

You can simply create an array using one of the below approach.

a) Using an array literal is the easiest way to create a JavaScript Array.

const array_name = [item1, item2, etc];   

b) Using the JavaScript Keyword new

const fruits= new Array("Mango", "Apple", "Orange");

Note: Array indexes start with 0.

[0] is the first element, [1] is the second element and [Array.length-1] is last element.

Let us deep dive to learn more about array using a below example:

const fruits= new Array("Mango", "Apple", "Orange");

Accessing Array Elements:

console.log(fruits[0]);

Output: Mango

Changing an Array Element:

fruits[0]="Banana";

console.log(fruits[0]);

Output: Banana

converting an array to String:

console.log(fruits.toString());

Output: Banana,Apple,Orange

Adding Array Elements:

fruits.push("Lemon");

To check if the Javascript object is array, we can use Array.isArray() as shown below:

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

Output: True

One way to loop through an array, is using a for loop which we learn in previous blog post.

we can can also use the Array.forEach() function as shown below.

const fruits= new Array("Mango", "Apple", "Orange");

var text="";

fruits.forEach(myFunction);

function myFunction(value) {

  text = text + value + " ";

}

console.log(text);

Output:

Mango Apple Orange

No comments:

Post a Comment