What is an Array:
- An array is a collection of values stored in a single variable. Instead of creating multiple variables:
let a = 10;
let b = 20;
let c = 30;
we can use Array:
let numbers=[10,20,30];
Creating an array using literal:
Creating Empty Array:
let a=[];
console.log(a);
Initalize values:
let b=[10,20,30];
console.log(b);
O/P:
[]
10,20,30
Creating using new Keyword(constructor):
let a= new Array(10,20,30);
console.log(a)
O/P:
[10,20,30]
1. Accessing Elements of an Array:
Any element in the array can be accessed using the index number. The index in the arrays starts with 0.
let fruits = ["apple", "banana", "mango"];
Using index:
console.log(fruits[0]);
O/P:
apple
First element:
let a=fruits[0];
console.log(a);
O/P:
apple
Last element:
let last=fruits[fruits.length-1];
console.log(last);
O/P:
mango
2. Modifying Array elements:
let fruits = ["apple", "banana", "mango"];
fruits[1] = "orange";
console.log(fruits);
O/P:
["apple", "orange", "mango"]
3. Adding Elements to the Array:
- Elements can be added using push() and unshift() methods
push() → add at end
fruits.push("grape");
O/P:
"apple", "banana", "mango", "grape"
unshift() → add at beginning
fruits.unshift("kiwi");
"kiwi", "apple", "banana", "mango", "grape"
4. Removing Elements from an Array
- To remove the elements from an array we have different methods like pop(), shift(), or splice().
pop() → remove last
fruits.pop();
shift() → remove first
fruits.shift();
5. Array Length:
let fruits = ["apple", "banana", "mango"];
console.log(fruits.length);
O/P:
3
6. Increase and Decrease the Array Length:
let fruits = ["apple", "orange", "kiwi"]
console.log(fruits.length);
fruits.length=7;
console.log(fruits);
O/P:
3
7 ['apple', 'orange', 'kiwi', empty × 4]
7. Iterating Through Array Elements
We can iterate array and access array elements using for loop and forEach loop.
let fruits = ["apple", "orange", "kiwi"]
for(let i=0;i<fruits.length;i++){
console.log(fruits[i])
O/P:
apple
orange
kiwi
8. Array Concatenation
let fruits = ["apple", "orange", "kiwi"]
let basket=[1,2];
console.log(fruits.concat(basket));
O/P:
['apple', 'orange', 'kiwi', 1, 2]
9. Conversion of an Array to String
We have a builtin method toString() to converts an array to a string.
let fruits = ["apple", "orange", "kiwi"]
console.log(fruits.toString());
O/P:
apple,orange,kiwi
Top comments (0)