JavaScript – Array


Array is a collection that holds many things inside of it.

In JavaScript you can declare an array in two ways:
First way:

Second way by using array literal syntax:

To put some values inside of it, use commas to separate the values:

In JavaScript arrays are zero based, meaning the first element inside of it can be retrieved by index 0 ( zero ), the second by index 1 and so on;

JavaScript is a dynamically typed, thus it figures out what types of things are on the fly.
When you declare an integer or char in C programming language(java,c++,…) you have to declare the type of the variable before using it, but in JavaScript this is not the case, and you just need to write var keyword before the name of the variable and the JavaScript engine figure out what it is type dynamically on the fly.

So arrays can hold not just one of a particular data, it can also hold many different data types in the same array.
For example you can hold bool, array, number, string, object data types like this:

You also can put a function expression as an item inside an array:

Remember readable code is easier to change and maintain later, so let’s improve the above code to be more readable and cleaner:

Click here to run the above code

Notice that a function expression in the above array will be created on the fly, because JavaScript will recognize that it’s not a function statement.
The reason why you can put function expression in an array, because functions are Objects in JavaScript.

So JavaScript arrays can contain many different data types inside of it without any problem.

More important to know, that JavaScript array is Object, yes it’s Object.
Here some of it’s properties you already used before:

Another helpful methods of array: pop, sort, reverse, shift, slice, splice, indexOf….

As we said in the first of the post, JavaScript arrays accessed by indexes of type of number.
So what if we are trying to access an element using value of type of string?

As you saw, we got the same results, why this happened?
This occurred because as default JavaScript engine coerce(convert) the numbers to strings if we use indexes in the array as numbers primitive type, so every time we write myArr[2] or any other number value inside the square brackets, it’s coerced to string like this: myArr[“2”].

Don’t forget to correct me if any information is wrong.
Thanks, and comments are very welcome.


Hello, I'm Mohammad Daka, software engineer who love coding. In my spare time I blogs about JavaScript,PHP, Chrome Extensions, helpful resources and tools, I'm also working on my own projects. Don't hesitate to contact me at my twitter account: @mohammad_daka :)

You may also like...