Array Methods In JavaScript

in STEMGeeks2 years ago


Image Source

In my last post, I discussed about basic concept of Array. In this post, we will see various of built-in method that you can use in JavaScript for array. The first method we are discussing is length. It is used to find the lenght of an array. Consider the following code:

<!DOCTYPE html>
<html lang="en">
<title>Array Method</title>
    var chicken_dish = ["Drumstick", "Roast", "Nugget", "Tandoori", "Grilled wings"]
    document.write("<h4>" + chicken_dish.length + "</h4>")

We have declared an array called chicken_dish with five string values. If you see the output in the browser, you can see 5 as below:


To access the value at particular position we just write the array_name followed by square bracket where index number is written. For example: alert(chicken_dish[3]) will show pop-up with "Tandoori" as arrya index value starts at 0.

If you want to update the particular value you can write as follow: chicken_dish[2] = "Chicken Chilli";. It will update the value Nugget with Chicken Chilli.

Another method you can use to insert new value to your existing array is using push() method that will add the new value at the end of array. For example:

chicken_dish.push("Crispy Chicken");

If you print the current array, you can get the following output:


Using pop() method will remove the value at the end of array. In our case above, Chicken Chilli will be removed.

Another popular method is concat() that helps to combine two or more arrays into one.


" + chicken_dish.concat(["Crunchy Chicken", "Chicken Lollipop", "Chicken Kebab"]) + "


The above expression returns a new array with the following value. The old array remains the same and is unmodified.


Another method is sort() that is used to sort the value inside the array and can be applied for numberical or alphabetical array. If we want to sort our original chicken dish array, we say chicken_dish.sort(). The output can be seen as below:


Other method that you can use are:

  • reverse(): Used to reverse the order of the value within the array.
  • indexof(): Used to return the index of particular value in the array. The value goes inside the parenthesis.
  • includes(): Returns a boolean value if the value written inside the parenthesis is found.