Skip to main content

java script Arrays


Hi everyone.👋
This is my 10th js tutorial which is explain about Arrays in java script.
If we consider an array as an object we can store multiple values of data in same type.

This is the syntax for array
var myArray = [“dog”,”cat”,”lion”,”monkey”,”tiger”];
or
var myArray = new Array (“dog”,”cat”,”lion”,”monkey”,”tiger”);
So according to this array elements can identify as
myArray[0] = dog🐶
myArray[1] = cat🐱
myArray[2] = lion🦁
myArray[3] = monkey🐵
myArray[4] = tiger🐯

There are some properties of arrays that we can use them for various conditions.

length property      = can get the array size
index property       = can get the element that indexes from zero
prototype property = this property allows to add properties and methods to any object



Figure 1

This is the result:

Figure 2
This prototype property is very important property in arrays. We can use it in various places which is used to add new properties to the arrays.
Also there are some pre define functions that use in arrays. Here I have listed some pre define methods.

  1.              concat()
  2.             filter()
  3.             indexOf()
  4.             forEach()
  5.             join()
  6.             push()
  7.             reduce()
  8.             reverse()
  9.             toString()


Now I’m going to explain some methods selected randomly with simple examples.
concat() method


Figure 3
Here I have defined two arrays arr1 and arr2. We can bind two arrays using concat method. Also we can bind an array with any variable using cancat method that show in the source code.this is the result of above code.

Figure 4

join()
Using join method we can make one string from all the elements in the array. As shown in the below code.

Figure 5

OK Can you guess what is the result of this join method.
Yes it will be a, b, c, d, e, f.
Here it is.

Figure 6

If you use myArr.join(“+”)
The resut will be
a + b + c + d + e + f

push()

Push method allows to add new elements to the array and generate a new array. Like this.
<script type="text/javascript">
var myArr= new Array(1,2,3,4);
var newArr= myArr.push(5);
var finalArr= newArr(20,29,80);
</script>

The result of this code is
newArr  = 1,2,3,4,5
finalArr  = 1,2,3,4,5,20,29,80

reverse()

This method allows to reverse an given array
var arr = [0, 1, 2, 3].reverse();
Will produce output as 3, 2, 1, 0
There are lots of array methods in java script and we will meet them in the examples we do in the future tutorials. Neither you may be bored to read this tutorial when it is too long. You can try these examples and after it you can search about other predefine methods.
Thankyou !

Comments