How to define and assign values to JavaScript arrays.

Array in JavaScript

Arrays are variables that can store ordered collection of values in them which can be of different data types, with each having a numeric position known as an index.

JavaScript follows a zero-based indexing scheme, meaning the index of the 1st element will start from 0, 2nd element will have the index 1 and, so on.

The variable name, followed by square brackets tells JavaScript that, this variable is an array.

Different types of value that we can store in the array is:

  1. String
  2. Number(Integers, floating points)
  3. Boolean
  4. Object
  5. Other arrays

So, let’s see how to do it.

Define Array in JavaScript Code

To create an array we need to declare a variable with ‘ var’ keyword and let JavaScript know that it is an array.

For that, we have two options: using square brackets [] or, the ‘new’ keyword.

//Example
var myArray = []; //Method 1
var animals = new Array(); //Method 2

JavaScript – Initialize Array

For Method 1:

var myArray = ["john", 23]; //Method 1

For Method 2:

var animals = new Array("cat", "tiger", "lion"); //Method 2

Assign Value to Array

For this example, let us take the array list so we want to assign a new value to our array list

We can do it in two ways.

Using indexes:

We can use indexes to assign values to the arrays.

Eg.

animals[5] = "kiwi";

console.log(animals); //Prints: "cat", "tiger", "lion", undefined, undefined, "kiwi"

Here, we can see that there are some undefined values are present in our array because when we work with indexes we are creating space regardless if it is the last position of our array, so we use push() method as mentioned below.

Using push() method:

The push() method allows us to add elements at the end of the arrays but unlike using index values, it does create any ‘undefined’ values in our array “animals”.

animals.push("kiwi", "panther", "leopard");

console.log(list); // Prints: "cat", "tiger", "lion", "kiwi", "panther", "leopard"