'How to initialize a JavaScript array with constant values?

How do you initialize a JavaScript array with constant values? For example, in C code I can write

int array[] = {1, 2, 3};

What is the equivalent in JavaScript?



Solution 1:[1]

1: Regular:

 var myCars=new Array(); 
 myCars[0]="Saab";       
 myCars[1]="Volvo";
 myCars[2]="BMW";

2: Condensed:

 var myCars=new Array("Saab","Volvo","BMW");

3: Literal:

 var myCars=["Saab","Volvo","BMW"];

Refer this link: https://www.w3schools.com/jsref/jsref_obj_array.asp

Solution 2:[2]

I am assuming your objective is to get an immutable array.

Note: in the javascript arrays are also object.

we can achieve this by using Object.freeze or Object.seal

'use strict'

const simpleObject =  {
  ADD_TODO : "ADD_TODO",
  DELETE_TODO :  "DELETE_TODO"
}

const immutableObject =  Object.freeze(simpleObject);

// now you can`t do update, delete or add in "immutableObject"

Kindly read the MDN documentation for more detail

Solution 3:[3]

In the following way:

var array = [1, 2, 3];

Read more about arrays in MDN:

Solution 4:[4]

Array object in javascript :

var mycars = new Array();
mycars[0] = "1";
mycars[1] = "2";
mycars[2] = "3";

or

var myCars=["one","two","three"];

Solution 5:[5]

try this:

var array = [1,2,3];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan Bormann
Solution 2 Abdul Rehman Kaim Khani
Solution 3 VisioN
Solution 4 Amrendra
Solution 5 Manish Mishra