Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to initialize an array in JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Initialization of Array in Javascript: We need to initialize the arrays before using them up and once the arrays are initialized various other operations can be performed on them.

Array initialising

There are two ways of initializing arrays in Javascript

  • Using array as literals
  • Using array as an object/array as a constructor

 

Using array as literals: It is easy to initialize arrays as literals as they can be directly initialized using commas and enclosed in square brackets. 

Example:

Javascript




<script>
   const sports = ["cricket", "football","competitive-programming"];
   console.log('sports=',sports);
     
   const myArray = [];
   console.log('myArray=',myArray);
     
   const score = [420, 10, 1,12,102];
   console.log('score=',score);
</script>

Output:

sports= [ 'cricket', 'football', 'competitive-programming' ]
myArray=[]
score= [420, 10, 1, 12, 102]

Example 2: The line breaks and new lines do not impact arrays, they store in their normal way.

Javascript




<script>
   const sports = ["cricket",
                   "football",
                   "competitive-programming"];
   console.log('sports=',sports);
     
   const myArray = [];
   console.log('myArray=',myArray);
     
   const score = [420, 
                  10,
                  1,
                  12,
                  102];
   console.log('score=',score);
</script>

Output:

sports= [ 'cricket', 'football', 'competitive-programming' ]
myArray=[]
score= [420, 10, 1, 12, 102]

Using array as an object/array as a constructor: Initialising an array with Array constructor syntax is done by using the new keyword. The similar array which was described earlier can be also declared as shown below.

Example:

Javascript




<script>
   // Using the new keyword
   const sports = new Array("cricket", "football", "competitive-programming");
   console.log('sports=',sports);
     
   var myArray = new Array();
   console.log('myArray=',myArray);
     
   const points = new Array();
   console.log('points=',points);
     
   const score = new Array(140, 200, 21, 53, 245, 20);
   console.log('score=',score);
</script>

Output:

sports= [ 'cricket', 'football', 'competitive-programming' ]
myArray=[]
points= []
score= [140, 200, 21, 53, 245, 20]

My Personal Notes arrow_drop_up
Last Updated : 21 Nov, 2022
Like Article
Save Article
Similar Reads
Related Tutorials