6

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?

0

5 Answers 5

12

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I too think Zoran's question means how to make the values inside the array immutable and your suggestion seems to be the answer as Javascript appears to have no way to use the const keyword for the values in an array or the members within an object.
1

In the following way:

var array = [1, 2, 3];

Read more about arrays in MDN:

Comments

1

Array object in javascript :

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

or

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

2 Comments

In general it is preferable to use the literal notation of the other answers, when all initial values are given.
he is new.so just for his knowledge.
1

try this:

var array = [1,2,3];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.