Javascript Fundamentals: Arrays

Tags: javascript

I'm big on fundamentals.  I like to review fundamentals over and over because well, they're fundamental.  Not only that... you discover things you may have missed the first or second or 12th time you worked with that technology.

Javascript arrays are the topic here.  Let's dig in.

Creating Arrays

The full blown syntax

var things = new Array("A","B","C")
console.log(things);
result:  ["A", "B", "C"]

Omitting the new keyword, no problem

things = Array("AA","BB","CC")
console.log(things);
result: ["AA", "BB", "CC"]


You can even omit the new keyword and the Array keyword

things = ["A","B","C"]
console.log(things);
result:  ["A", "B", "C"]

Javascript arrays can contain multiple types.  Is that awesome or crazy?  You decide

things = new Array(1,"B","C")
console.log(things);
result: [1, "B", "C"]


Accessing Array Elements

Access an element by subscript notation

things = new Array("A","B","C")
console.log(things[2]);
result: ["A", "B", "C"]


Accessing a missing element does not throw an error

things = new Array("A","B","C")
console.log(things[3]);
result: undefined

Sizing Arrays

You can initialize the length of an array like so

things = new Array(12)
console.log(things.length);
result: 12


And change the length of an array like so

things = new Array("A","B","C")
things.length = 5;
console.log(things.length);
result: 5


And if you add an element beyond the length, it will automatically expand, no error

things = new Array("A","B","C")
things[26] = "Z"
console.log(things[26]);
result: Z


Append a value to the end of an array like so

things = new Array("A","B","C")
things[things.length] = "D"
console.log(things);
result: ["A", "B", "C", "D"]

Converting to a String

Listing out an array as a string

things = new Array("A","B","C")
console.log(things.toString());
result: A,B,C

Listing out an array as a string with custom delimiters

things = new Array("A","B","C")
console.log(things.join("||"));



Plunk of these examples

More javascript:  Javascript Fundamentals: Variables and Hoisting


No Comments

Add a Comment