1

A variable declaration and assignment is possible to do within a line, but it seems not possible to do with an array, why?

var variable1 = 5;  // Works

var array1[0] = 5;  // Doesn't work

var array2 = [];    // Works
array2[0] = 5;
2
  • It doesn't work because when you declare array1[0], it is trying to set the zeroth element of array1, which does not exist Commented May 22, 2014 at 2:17
  • Did you declare array1 as an array? var array1 = []; Commented Jul 1, 2014 at 16:23

5 Answers 5

2

An array initialiser has the form:

var a = [5];

When you do:

var array1[0]

then the interpretter sees var and expects it to be followed by an identifier. However, array1[0] is not a valid identifier due to the "[" and "]" characters. If they were, you'd have a variable named array1[0] that has the value 5.

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

Comments

1

var array1 = [5]; initializes array1 to an array literal with a single element 5.

Note that array1 is not a constant array, elements can be pushed, read, changed, etc.

The above line has the same effect as

var array1 = [];
array1[0] = 5;

Comments

1

You almost had it:

var array2 = [5];

Comments

0

You can't use var when pushing to an array because it interprets as "array1[0]" - using characters that aren't allowed, but also you need to set the array first

var array1 = [];
array1[0] = 5;  // Yes it does

console.log(array1);

Comments

0

Because it's just the wrong way, i guess.

var array1 = [5];
var array2 = [3,4,5];

is the way you wanna do it.

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.