Dynamic Array in JavaScript

Mehvish Ashiq Oct 12, 2023
  1. Static Array vs. Dynamic Array in JavaScript
  2. Use prompt() to Create Dynamic Array in JavaScript
  3. Use <input> Tag to Create Dynamic Array in JavaScript
  4. Use DOM Elements and jQuery to Create Dynamic Array in JavaScript
Dynamic Array in JavaScript

Can we create arrays dynamically in JavaScript? Yes, of course, we can.

This article gives examples about creating a dynamic array in JavaScript; it is necessary to understand static array vs. dynamic array.

Static Array vs. Dynamic Array in JavaScript

Normally, we determine the array size or length while creating it; this array type is a static or fixed array. On the other side, the dynamic array means allocating the memory and populating the values at run time.

They can also update their size at run time, which overcomes the limitation in static arrays.

Use prompt() to Create Dynamic Array in JavaScript

For creating dynamic arrays, we can take input from users in two ways, the first is prompt(), and the second is <input> element.

The prompt() method reveals a dialogue box that reminds users to input a value. If the user clicks OK, the prompt() method returns the input values, otherwise null.

On the other hand, we can also use the <input> tag to take input from the user. It is an HTML element and has various types.

We’ll be using <input> of type=text. Let’s start with the example that uses prompt().

JavaScript Code:

var inputArr = [];
var tempVariable = '';
do {
  tempVariable = prompt('Enter a number. Press cancel or leave empty to exit.');
  if (tempVariable === '' || tempVariable === null) {
    break;
  } else {
    inputArr.push(tempVariable);  // the array will grow dynamically
  }
} while (1);
document.write(inputArr);

Output:

dynamic array in javascript - output one

Here, we exit the code if the input is empty or null; otherwise, insert the input value into inptuArr using the push() method.

Use <input> Tag to Create Dynamic Array in JavaScript

In the following example code, we use the <input> element to take input from the user and populate it in the array at run time.

HTML Code:

<html>
	<head>
 		<title>Document</title>
 	</head>
 	<body>
 		<input type="text" id="num" />
 		<input type="button" id="addBtn"onclick="addValues();" value="Add" />
 		<br />
 		<input type="button" id="showBtn" onclick="showValues();" value="Show" />
 		<div id="container"></div>
 	</body>
</html>

CSS Code:

#addBtn{
 background-color: lightgreen;
}
#showBtn{
 background-color: orange;
}

JavaScript Code:

var arr = [];

function addValues() {
  var input = document.getElementById('num');
  if (input.value == '' || input.value == 'null')
    alert('The element can\'t be empty or null');
  else
    arr.push(input.value);
  input.value = '';
}

function showValues() {
  var html = '';
  for (var i = 0; i < arr.length; i++) {
    html += '<div>' + arr[i] + '</div>';
  }
  var container = document.getElementById('container');
  container.innerHTML = html;
}

Output:

dynamic array in javascript - output two

Here, we check the input value when the user presses the Add button. If it is empty or null, we alert the user and enter the input again.

The Show button displays all the elements of the array.

Use DOM Elements and jQuery to Create Dynamic Array in JavaScript

Create and populate a dynamic array using DOM elements. Let’s use jQuery to understand how we can do that.

HTML Code:

<html>
 	<head>
 		<title>Document</title>
 	</head>
 	<body>
 		<ul id="filelisting">
 			<li><a href="path/to/file1.docx">File Title1</a></li>
 			<li><a href="path/to/file.docx">File Title2</a></li>
 			<li><a href="path/to/file3.docx">File Title3</a></li>
 		</ul>
 	</body>
</html>

JavaScript Code:

var fileList = [];

$('ul#filelisting li a').each(function() {
  fileList.push({File_Title: $(this).text(), File_Path: $(this).attr('href')});
});
console.log('The content of the array is given below:');
console.log(fileList);

Output:

"The content of the array is given below:"
[{
 File_Path: "path/to/file1.docx",
 File_Title: "File Title1"
}, {
 File_Path: "path/to/file.docx",
 File_Title: "File Title2"
}, {
 File_Path: "path/to/file3.docx",
 File_Title: "File Title3"
}]
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Array