Javascript Array Variable Types – POFTUT

Javascript Array Variable Types


While programming we generally need to use multiple even several hundred variables of single type. Should we define one variable for each value? No. We can use arrays which can hold multiple values in a single variable. An array is string of values. So it gives the flexibility to store more than one data into single variable. An array can be defined like below.

var names=new Array("ismail","ahmet","elif");
  • var tag variable
  • names is array
  • new Array creates new array with specified values. Each value have to separated
var fruits=["apple","berry","lemon"];
  • This is simpler definition of the array there is no difference.
  • [ ] is used to surround array elements

Arrays element count can not be more than 4,294,967,295.

Index

As we have learned that arrays have multiple elements. Index is used to specify only one element in an array.

var fruits=["apple","berry","lemon"];
console.log(fruits[1]);
  • We want to get berry and use [ ] to specify index 1.
  • Arrays indexes starts from 0
berry

Get Length of Array

Arrays size can be changed while using the by adding or removing elements. Array size can be get with length

var fruits=["apple","berry","lemon"];
console.log(fruits.length);
  • length gets the length of the array
3
  • We have three elements

 Joining Two Arrays

Two arrays can be joined together with concat method of array.

var fruits=["apple","berry","lemon"];
var numbers=[1,2,3];
var joined=fruits.concat(numbers);
console.log(joined);
  • Fruits array concat function is used to join numbers array.
  • Joined is new array consist of fruits and numbers
[ "apple", "berry", "lemon", 1, 2, 3 ]

Find Element Index of Array

We can get the index of element with indexOf function. We will provide the element value.

var fruits=["apple","berry","lemon"];
fruits.indexOf("berry")
  • We use indexOf function and provide “berry” as element. This will return
1
  • The result of the indexOf will be 1
LEARN MORE  How To Enumerate In Python Programming Language?

Add Element To Array

Adding element to an array can be done with push function.

var fruits=["apple","berry","lemon"];
fruits.push("melon")
  • Melon is added to the fruits array with push function
[ "apple", "berry", "lemon", "melon" ]
  • This is our final fruits array

Remove Element From Array

Removing element from array is done with pop function. Pop function will return the last element of the array by removing. Keep in mind that this will return last element as a result too.

var fruits=["apple","berry","lemon"];
fruits.pop();
  • pop function removes lemon from array and returns it

Leave a Comment