Home » JavaScript

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,

Code

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.

Code

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.
console.log(inputArray);

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.