Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't an array variable have to be declared with `new Array`?

Tags:

javascript

While reading a book about JavaScript I stumbled across an example:

var names = new Array("Paul","Catherine","Steve");
var ages = new Array(31,29,34);
var concatArray;
concatArray = names.concat(ages);

My question is, why doesn't the variable concatArray need to be define as a new Array() in order to store the concatenated data for both arrays name and ages, but when I try to treat the concatArray as an array by adding another line of code "document.write(concatArray[0])", it works just like an array and shows me the data stored in the first element. I just wonder why I'm not declaring the concatArray as a new array, yet it still works as one.

like image 818
caramel1995 Avatar asked Mar 23 '26 03:03

caramel1995


1 Answers

You are declaring concatArray as a new array but the declaration is implicit. The concat function returns a new array which contains concatenated copies of the original two arrays. The type of concatArray is inferred from the return type of the concat function.

like image 86
Andrew Hare Avatar answered Mar 24 '26 15:03

Andrew Hare