JavaScript Arrays

JavaScript Arrays are kind of unique data structure, as these are just JavaScript Objects but property names being index(integer). Index for JavaScript arrays uses 32-bit number system meaning JavaScript’s arrays index can vary from 0 to 232-2 totalling 4,294,967,295 elements in an array, that’s why JavaScript array can hold a lot of data.

Below are some common features of JavaScript arrays –

  • JavaScript arrays are zero-index based, meaning first element of array have index 0.
  • Owing to using 32-bit number system for index, JavaScript arrays can hold a lot of data(4,294,967,295 elements in a single array).
  • Array elements does not need to be of same type, some elements can be integer or boolean or even JavaScript Objects as well.
  • JavaScript arrays are dynamic meaning their size is not fixed and can change(increase/decrease) as needed in the program.
  • Because arrays are dynamic that’s why as a Developer you don’t need to declare size of array before hand – this makes JavaScript Programming Language a little easier.

Moreover as Arrays are just JavaScript objects that’s why these also inherit properties from internally defined Array class – Array.prototype. This idea of objects inheriting certain functionalities from internally defined data structures is called JavaScript Prototype Chain.

Ways to create Arrays in JavaScript

There are multiple ways in which arrays can be created in JavaScript, simplest and my favourite one being – Listing comma separated elements within square brackets. JavaScript syntax for this is [ 1, 2, 4, 5]. Boom we have an array of length four containing integers 1, 2, 4, 5. Using this way literally any possible type of array can be created.

Using Square Brackets[ ] Syntax for making JavaScript Arrays

Below are some code examples of JavaScript arrays made using square brackets syntax.

var cars = ["Tesla", "Hyundai", "Porsche"]; // Simple array of strings
var int = [1, 2, 4, 5, 6, -29, -10]; // Array of integers
var mixed = ["Tesla", 3, 4, true, -10, false]; // Array of mixed data types
var weird_array = [[1, 2, 4], { x:1, y:3 }, "Computer Science Hub"]; // Array having array, object, string

In the above example, I mentioned about Data Type and Objects. If in case your not aware about JavaScript Data Types or JavaScript Objects. Then please check out these articles first then come back to this article and learn about JavaScript Arrays.
• For learning about JavaScript Objects – Objects in JavaScript
• For learning about JavaScript Data Types – Boolean, Strings, Numbers.

Let’s get again back to Ways in which arrays can be created in JavaScript Programming Language. Using just Square Brackets is quite easy, but there does exist other way which is constructor Array(). The array which this constructor creates depends upon with what arguments is passed to this when it’s called.

Invoking construtor Array() with no arguments

If no arguments is passed and Array() this is called then an empty array will be created(Same as [ ], empty square brackets).

var x = new Array();
// Here x will be an empty array

var x = [];
// Empty square brackets also create an Empty JavaScript array

Calling Array() passing on single positive number

If constructor Array() is called and just a single positive integer is passed to it, then constructor will create a JavaScript array of length equals to positive integer passed to it as argument.

var x = new Array(3);
// x will be a JavaScript array of length 3
// x will be empty does not have any element on index 0,1,2

For var x = new Array(3); if you try to access value at say index 0, then it will return undefined. Meaning new Array(3) is just allocating memory for holding three elements.

Passing more than one element to constructor Array()

If you pass more than one arguments to JavaScript constructor Array() then it will create an array containing passed arguments as elements. For example – new Array(1, 2, 3); will create an array [1, 2, 3]. Here arguments can be anything may be objects, strings or numbers. Like new Array(2, 4, “Computer Science Hub”, “Hello”, { x:1, y:10 }); will create an array [2, 4, “Computer Science Hub”, “Hello”, { x:1, y:10 }].

How to create an empty array in JavaScript?
An empty array in JavaScript can be created using empty square brackets[ ] or by calling Array() JavaScript constructor with no argument. Here [ ] or Array() is an empty array of length zero.

How to create an empty array of any size?
Empty array of some size/length in JavaScript can be created using commas inside square brackets like [ , , , , , ] or calling JavaScript Array() constructor with some number like Array(10) will create an empty array of size 10.

Ways to read/write array elements in JavaScript

I hope that so far you have learned How to create a JavaScript Array? now next question arises as these arrays can hold a lot of data(maximum 4,294,967,295 elements in a single array). How to exactly write data to an array or read data from it, if data cannot be read from array then what’s purpose of having Array Data Structure at all in JavaScript.

How to read elements of a JavaScript array?
Simply add square brackets after name of array and pass index inside these brackets. For example – In order to access element at index 0 from var x = [1, 5, 10, 20]; simply do x[0];

How to write elements to an array in JavaScript?
Elements to an array can be written using array_name[index] = value; statement. Like if you have an array var x = [ 10, 9, 45 ] then writing an element at index 3 can be done as x[3] = “Computer Science Hub”; after this array x will become [ 10, 9, 45, “Computer Science Hub”]

Please do note reading/writing elements to an array can be quite confusing sometimes as JavaScript treats Arrays as Objects and also JavaScript do type conversation of various identities internally.

  1. var x = [ 10, 2, 4 ] if we do x[“value”] = 100 then JavaScript will assign 100 value and create a new property for x object. But still array will remain [ 10, 2, 4 ], if you try to read x[“value”] then 100 will be returned but it’s not in array rather its property of array.
  2. var x = [ 100, 46, 28 ] if we do x[“5”] = “Hello” then here JavaScript internally will convert “5” string to number 10 and assign index 10 of array x value “Hello”. So array x will become [ 100, 46, 28, , “Hello”].
    Note here that index 4 will be empty.
  3. var x = [ 36, 29, 183 ] if we do x[-5] = 100 then JavaScript internally will change -5 number to -5 string and would assign -5 as property with value 100 to array x. So array still will be [ 36, 29, 183 ] but if you do x[“-5”] then 100 number be returned.

Please look at three above points, as I’ve seen my colleague JavaScript Developers make a lot of mistakes about reading/writing data to an array. This could cause serious problems as well in code.
Read more about JavaScirpt Object’s Properties here – Properties of JavaScript Objects.

Determining length of JavaScript Arrays

Arrays in JavaScript are quite handy as these can hold a lot of data(4,294,967,295 elements in a single array), meaning that JavaScript arrays can be quite small as well as very large sometimes. That’s why knowing length of array can be handy for not only accessing elements but it can be helpful for updating/adding newer elements to array as well.

  • Length of JavaScript’s array is often equal to number of elements in it unless array is sparse(An array having some undefined elements)
  • Highest index of element in an array will be always one less than length of array, but not for Sparse Arrays.
  • For general arrays length > highest element’s index

Sparse Arrays in JavaScript
Those JavaScript arrays which have some undefined elements. For example – [1, , 2, 3, 4, , , 7 ] is a sparse array as elements at index 1,5,6 are undefined.
Length of sparse array is always less than highest index number in array. Like for [1, , 2, 3, 4, , , 7 ] length is 5(Because it have 5 elements) but highest index is 7.

Dense Arrays in JavaScript
These are kind of opposite to a sparse arrays, as in Dense Array every index must have an element. For example – [ 10, 20, 30, 40 ] is a dense array whilst [ 10, , 30, 40 ] is not a dense array.

What is JavaScript’s length property(.length)?

.length property of JavaScript Array object can be called upon it, for getting length of array. For example – [1,2,3,4,5].length will return 5 while [ ].length will return 0 as array is empty.

Not only .length can be used for determining length of a JavaScript array rather it can also be used for increasing/decreasing length of it as well.

  • Decreasing length of array using .length – For example if you have array var x = [3, 4, 6, 7,8]; then doing x.length = 2; will chop the array and now array x will be [3, 4]
  • Increasing length of array using .length – If you have an array defined something like var y = [10, 40, 50, 39, 20] then doing x.length = 7; will add two undefined elements and now array will be [10, 40, 50, 39, 30, , ]

Updating JavaScript array elements(Adding/Deleting elements from an array)

Changing elements inside a JavaScript array is quite simple. For adding elements to a JavaScript Array simplest approach can be –

x = [] // An empty JavaScript array
x[0] = "Computer Science";
x[1] = "Hub";

// Now array x will be ["Computer Science", "Hub"] 

Moreover there’s an another way to add elements to end of an array, which is using .push(). For instance if you have an array like [ 1, 2, 3 ] then doing [ 1, 2, 3 ].push(“Hello I was pushed”); then array will become [ 1, 2, 3, “Hello I was pushed”].

Note – .push() can add elements to end of array only.
There are many other ways as well in JavaScript for adding/deleting elements from JavaScript arrays. Some of methods for adding/deleting elements from JavaScript Arrays –

  1. delete operator – Using delete an element from specific index in array can be removed. If you have an array x as [10, 405, 20, 19] and want to remove element at index 0 then do delete x[0]. This will not remove index 0 from array x rather it will assign value undefined to index 0 in array. So now array x becomes [ , 10, 405, 20, 19] and if you access element at index zero now x[0] it will return undefined.
  2. unshift() javaScript array method – This JavaScript array method adds element at start of array and pushes other elements to higher index. For example if you have [ 10, 20, 46, 29 ] then doing [ 10, 20, 46, 29].unshift(“Computer Science Hub”) will change array to [ “Computer Science Hub”, 10, 20, 46, 29].
    Each element in array have been shifted up by one index number.
    [ 10, 20, 46, 29 ] index of 10 is 0
    • [ “Computer Science Hub”, 10, 20, 46, 29] index of 10 is 1
  3. shift() array method in JavaScript – If called on an array this method will remove first element from array(value at index 0). Not only this method will removed first element but it also shift all other elements one index down. For example – Doing [ 62, 29, 19, 81 ].shift() will remove first element(62) from index 0, now array will become [ 29, 19, 81 ]. Moroever index of elements have shifted down by one.

delete operator will just remove value from array and replace it with undefined, while shift()/unshift() remove element and does not replace removed value with undefined.

Conclusion

JavaScript Arrays are quite useful as these can hold a lot of data and also these is not need to explicitly declare its length or type of elements it will contain beforehand. Owing to this arrays are quite useful.

I hope that this article helped you to better understand JavaScript Arrays, if in case you have any question about arrays in JavaScript then feel free to comment down below. I will try to reply as soon as possible.

Moreover if your learning JavaScript Programming Language, then I have put together a number of articles covering different aspects of language. You can check those articles here – JavaScript Programming language Computer Science Hub.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts