javascript

Array


 

An array is a data structure that stores a collection of elements. These elements can be of any data type, including numbers, strings, objects, or even other arrays.
Arrays in JavaScript are zero-indexed, meaning the first element is accessed with an index of 0, the second with an index of 1, and so on.

 

Declaring Array:

To create an array, we can use the array literal syntax, which involves enclosing the elements inside square brackets [].
 

// Declaring an empty array
let myArray = [];

 

Defining Array:

// defining an array with elements
let skills = ['javascript', 'php', 'dotnet'];

 

Defining Array:

// defining an array with elements
let skills = ['javascript', 'php', 'dotnet'];

 

Note:

Arrays in JavaScript can hold multiple data types making it complex data structure.

// Arrays can contain elements of different types
let mixedArr = [23, 'coders', true, { name: 'Rohit' }];

 

Accessing Array's Element:

// Accessing elements in an array
console.log(skills[0]); // Outputs: javascript
console.log(mixedArr[2]); // Outputs: true

 

Modifying Array:

// Modifying elements in an array
skills[1] = 'laravel'; // Modifying the second element
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet'];

 

Length of Array:

// Arrays have a length property
console.log(skills.length); // Outputs: 3

 

Adding in Array:

// Adding elements to an array
skills.push('python');
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet', 'python'];

 

Remove element from Array:

// Removing the last element from an array
let lastskill = skills.pop();
console.log(lastskill); // Outputs: python
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet'];

 

Iterating Array:

// Iterating over elements in an array
skills.forEach(function(skill) {
console.log(skill);
});