Array methods in JavaScript

You already have learned about previous chapter. There are many methods to operate on the array. Let us see them one by one.

push()

push method is used to add the value in array at last.
It returns new length of the array.


let arr = [1,2];
arr.push("3");
console.log(arr);
//output: [1,2,"3"]

arr.push("4",5);
console.log(arr);
//output: [1,2,"3","4",5]
                    

pop()

pop removes the last value from the array and returns that value.


let arr = [1,2,"3"];
let lastVal = arr.pop();
console.log(lastVal);
//output: "3"
console.log(arr);
//output: [1,2]

lastVal = arr.pop();
console.log(lastVal);
//output: 2
console.log(arr);
//output: [1]

let arr1 = [];
console.log(arr1.pop());
//output: undefined
                    

As you can see, pop returns the last value of the array. If array is empty, it returns undefined.

shift() method

shift removes the first element from the array and returns the value.


let arr = [1,2,"3"];
let firstVal = arr.shift();
console.log(firstVal);
//output: "3"
console.log(arr);
//output: [2, "3"]
                    

unshift()

unshift adds the pased value at the beginning of the array.


let arr = [2,"3"];
let length = arr.unshift(1);
console.log(arr);
//output: [1, 2, "3"]
console.log(length);
//output: 3

length = arr.unshift(3,5);
//output: 5
console.log(arr);
//output: [3,5,1,2,"3"]
                    

Just like push method, unshift can adds multiple value.

concat()

concat joins two arrays and returns a new array.
Remember, It doesn't change any array but returns a new array.


let arr1 = [1,2,3];
let arr2 = ["4","5","6"];
let arr3 = ["a","b","c"];

let result1 = arr1.concat(arr2);
console.log(result1);
//output: 1,2,3,"4","5","6"

let result2 = arr1.concat("x","y","z");
console.log(result2);
//output: 1,2,3,"x","y","z"

let result3 = arr1.concat(arr2, arr3);
console.log(result3);
//output: 1,2,3,"4","5","6","a","b","c"

let result4 = arr1.concat(arr2, "x","y","z");
console.log(result4);
//output: 1,2,3,"4","5","6","x","y","z"

                    

As you can see from above code snippets, you can pass arrays or values or both and all of them will be concatenated with the array on which the method is called ( In our case it is arr1 ) and the final array will be returned.
Remember, this method doesn't change any array, just returns the result.

join()

join method joins all the elements of the array with the provided delimiter.


let arr1 = ["hello","world","my","name","is","john"];
let result = arr1.join(" "); //space is provided as delimiter
console.log(result);
//"hello world my name is john"

result = arr1.join();
console.log(result);
//"hello,world,my,name,is,john"
                    

If you don't provide any delimiter, then "," will be used. Remember, it doesn't change array.

Conclusion

In this section, you have learned about different methods of arrays.
In next section, you will learn about user defined objects in JavaScript.