Introduction to Vectors in JavaScript
A vector is a special kind of array whose size can be increased or decreased based on the data stored in it. Vectors can hold any type of elements, objects and data types. It can be said that vectors are one-dimensional dynamic arrays. Due to its dynamic structure, it provides the ability to assign the structure size before-hand and enable memory space allocation quickly. Now we have defined what vectors are let’s understand why they are used.
Why Vectors are used in JavaScript?
Vectors have their values/items/elements stored in contiguous space, which implies that the items can be accessed using iterators as well as using offsets.
The points stated below explains to us why vectors are used even though we have arrays, and what benefits/features it provides that makes it useful in programming:
- Vectors can be used to store objects or a collection of objects in an organized fashion.
- The size of the vector can be provided upfront.
- Serves as a data structure container.
- It provides memory space allocation quickly.
- Dynamic in nature i.e. their size can be increased on-demand, unlike arrays, that have a fixed size.
- Accessing an item inside vector via an index in constant time, just like an array.
Examples of Vector in JavaScript
Let’s see how a vector can be created in JavaScript and its properties by going through some examples:
Example #1 – Creation of Vector in JavaScript
Code:
<!DOCTYPE HTML>
<html>
<body></body>
<script>
//Created new Vector - numBooks
var numBooks = ["firstBook","secondBook","thirdBook"];
for(var count = 0; count < numBooks.length; count++)
console.log("Printing Books - ",count,": ", numBooks[count]);
</script>
</html>
Output:
Explanation:
As seen from the above example the vector object – numBooks has the length property that gives the length of it based on the number of items present in it starting from position 0, same as an array.
Example #2 – Dynamic Nature of Vector in JavaScript
Code:
<!DOCTYPE HTML>
<html>
<body></body>
<script>
//Vector Defined
var shopItems = []
// Adding items to the vector
shopItems.push("Cornflakes");
shopItems.push("Toothbrush");
shopItems.push("Chicken");
shopItems.push("Detergent");
shopItems.push("Bread");
//Print Total Shopping Items
console.log("Shopping List : ",shopItems);
console.log("Capacity : ",shopItems.length);
//Removing latest added item
shopItems.pop()
console.log("New Shopping List : ",shopItems);
console.log("Capacity : ",shopItems.length);
//Representing as a single string value without double quotes
console.log(" ");
console.log("Final Shopping List - ",shopItems.join());
</script>
</html>
Output:
Explanation:
The method “push”, which is associated with the vector shop items, is used to insert value to it. Right after that, we have a method called “pop” to remove a value from it and it returns the last value of the vector i.e. the vector follows LIFO (Last In First Out) implementation. The method “join” builds a single elongated string from a string vector.
Example #3 – Retrieving Elements from Vector
Code:
<!DOCTYPE HTML>
<html>
<body></body>
<script>
//Vector Defined
var shopItems = []
// Adding items to the vector
shopItems.push("Cornflakes");
shopItems.push("Toothbrush");
shopItems.push("Chicken");
shopItems.push("Detergent");
shopItems.push("Bread");
shopItems.push("Eggs");
shopItems.push("Rice");
console.log("Final Shopping List - ",shopItems.join());
// Retrieve elements from a particular position
console.log("Item at 3rd Position - ",shopItems[2]);
//Search an item in the Vector
console.log("Apple at Position : ",shopItems.indexOf("Apple")); // -1 => Element Not Found
console.log("Bread at Position : ",shopItems.indexOf("Bread")+1);
</script>
</html>
Output:
Explanation:
In the above code sample, we first retrieved an element present at 3rd position, remember as an array vector indexing starts at 0, therefore we have mentioned shopItems[2] to get 3rd element in the vector list shop items. Next, in the code sample, we are searching if an item is present in the list or not by using the indexOf() method that returns an index position if an item is present in the vector or else it returns -1, implying that the item does not exist in the vector list.
Conclusion
In this article, we understood what vectors are, why is it used, how it differs from a typical array, how it works and acts in the JavaScript program context, with the help of some examples that we followed throughout this article. Also, we saw how to implement basic functionality like add, remove, retrieve, search an element in the vector.