JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Create a user defined array in JavaScript

In this article, we will learn how to take user input and store it in array for performing operations on it?
Submitted by Abhishek Pathak, on October 17, 2017

JavaScript is not a traditional programming language. It is a scripting language basically built for the web. It doesn't support standard input output stream, but using methods we can implement this functionality.

In JavaScript, we have a prompt() method which takes the user input through a popup and return the user entered data.

Here is an example,


var input = prompt('What is your Name?');

The parameter passed to prompt is the text that tells user what to do, just above the input field.

For our purpose, we are going to use this function and get the input from the user and store it inside the variable.


var inputArray = [];
var size = 5; //Maximum Array size

for(var i=0; i<size; i++) {
	//Taking Input from user
	inputArray[i] = prompt('Enter Element ' + (i+1));

//Print the array in the console.

In the above code, we have an empty array inputArray. Next we have a size variable which will be used to limit the iterations for defining a finite array size, because by nature arrays are dynamic in JavaScript.

In this loop, we take the inputArray[i] and store the return value from the prompt function. As the iterations increases, the size of array increase and user inputted value is assigned to array element.

Finally, we print out the value of the array using console.log(), but you can use this array for other purposes as well.

Hope you like the article. Share your thoughts in the comments below.

JavaScript Examples »

Related Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.