menardmam
menardmam

Reputation: 9986

Populating an array outside a function doesn't work

Here is a sample of what doesn't work:

var array_one = [];
array_one=['a','b','c'];

Declaring and populating the array outside any function doesn't work, but

var array_one = [];
function do_something(){
   array_one=['a','b','c'];
}

does, because it's inside a function. Why?

Upvotes: 1

Views: 192

Answers (2)

millimoose
millimoose

Reputation: 39950

array_one['a','b','b'] is not syntax to populate an array - I'm not really sure what it does actually.

If you do array_one = ['a','b','c'] then you replace the variable with a new array. (The difference between this and populating an array is that other references to the previous array will still have the old value.)

To add values to the array, use array_one.push('a').

Upvotes: 2

JaredPar
JaredPar

Reputation: 754585

What you're doing here is not initialization but instead member lookup. The expression is parsed as array_one[<member name>]. In this case member_name is achieved by evaluating 'a', 'b', 'c'. This uses the comma operator so the 3 expressions are evaluated in order and the result of the expression is the final expression: 'c'. This means your code is effectively doing the following

array_one['c'];

It sounds like what you want is instead

array_one = ['a', 'b', 'c'];

Upvotes: 4

Related Questions