CodrGeek is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our Privacy Policy Explore Now!

Create an array of given size in JavaScript

Creating an array of a given size can be implemented in many ways, and each way is useful in some conditions. We will explain each possible ways to create an array with the given size with a proper example.

Create an array of given size in JavaScript
Create an array of given size in JavaScript

Method 1: In this method, we use the JavaScript Array constructor to create an array. It will just create an array without any value with a given size. But the values of the array will be undefined.

<script>
	var arr = new Array(5);
	console.log(arr.length);
	console.log(arr)
</script>
Output:
5
[undefined, undefined, undefined, undefined, undefined]



Method 2: We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined.

<script>
	var arr = Array.apply(null, Array(5))
		.map(function () {});
		
	console.log(arr.length);
	console.log(arr);
</script>


Related Posts
Output:
5
[undefined, undefined, undefined, undefined, undefined]

About the Author

Hey there! My name is Mayank, a professional Blogger, Graphic Designer, Coder as well as Content Creator from Uttar Pradeh, India. I love to Code and create interesting things while playing with it.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.