JavaScript Arrays




Javascript has an Array object for storing and manipulating data in applications.  In the examples below I will be using Node.js to develop a simple Fibonacci sequence  number generator to help illustrate how and why you may want to use array’s in your software application.  The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . Each subsequent number is the sum of the previous two.

Creating an array object

There is 3 ways of creating arrays.

  1. Creating an array object
     
  2. Create an Array object by instantiating the Array object.
  3. create an Array object by inserting collection data

Inserting data

After creating an Array object, we can insert data. Use [] with index if you want to assign the value.

You can also use the push() function to insert data.

Accessing array values

To access array data, you can use [] with data index parameter.




Application example

I’ll create a simple node.js application which will illustrate how to make use of arrays. The code below includes a reference to simple Fibonacci sequence generator class which exposes two methods to generate a Fibonacci sequence, Looping or Recursion,  the source code for the class is included in the GitHub Repository.

 

Our console should print out

Updating data

To update an item of array data, you can use [] with data index and thus assign a new value.

Removing data

You can use the pop() function to remove data from the Array. The pop() method removes the last element from an array and returns that element.

If you want to remove data by specific index then you can use the splice()function.




Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.
π