Basic Syntax: Arrays

Using arrays to store collections of data.

Scroll down...

Content

Resources

Comments

In this lesson, we'll show you the sugar that JavaScript gives you when it comes to Arrays.

We recommend that you follow along with this lesson in your browser console and experiment with JavaScript yourself to test its boundaries

Codecademy Interlude

As usual, hop on over to Codecademy and complete the Data Structures section. Good luck!

The Basics

// A simple array with constructor.
var myArray1 = new Array( "hello", "world" );

// Literal declaration, the preferred way.
var myArray2 = [ "hello", "world" ];

// An empty literal declaration
var myArray = [];

// Adds "hello" onto index 0.
myArray.push( "hello" );  // the preferred way!

// Adds "!" on index 2
myArray[ 2 ] = "!";

// The gaps between 0 and 2 are now `undefined`
console.log( myArray );
//=> [ "hello", undefined, "!" ]
// or
//=> ["hello", 2: "!"]

// Popping off an element
// This is destructive, and removes that element
// from the original array.
myArray.pop()
//=> "!"

// Unshift back onto the front
// Returns the length of the array
myArray.unshift("!!")
//=> 3

// ...and shift it back out
// This is destructive, and removes that element
// from the original array.
myArray.shift()
//=> "!!"
myArray;
//=> ["hello", undefined]

Methods and Properties

var myArray = [ "hello", "world", "!" ];

// length is a *property* not a method here
// if it was a method, you'd call it with
// parentheses, e.g. `.length()`
myArray.length;
//=> 3

// You CANNOT just add arrays together!
[1,2] + [3,4];
//=> "1,23,4"

// ...use `concat` to combine them
[1,2].concat([3,4]);
//=> [1,2,3,4]

// Join the elements into a string with `join`
// which defaults to a comma separator or can
// take an option
[1,2].join();
//=> "1,2"
[1,2].join("");
//=> "12"
[1,2].join(",number!!!,");
//=> "1,number!!!,2"

// reverse the array
[1,2].reverse();
//=> [2,1]

// slice the array to return a new array
// from that index to the end of the old one
// this does NOT modify the old array
[1,2,3,4,5,6].slice(2);
//=> [3,4,5,6]

Sorting

Sorting the standard way is straightforward. But you can also pass sort a function. The function must show how to compare any two elements. If the return value is negative, the elements are kept in their same order and if it is above or equal to zero, they are switched:

// sort the array
[1,2,4,3].sort();
//=> [1,2,3,4]

// Comparison function
function descending( a, b ) {
  return b - a;
}

// putting it into action
var myArray = [ 3, 4, 6, 1 ];
myArray.sort( descending );
//=> [ 6, 4, 3, 1 ]

Splicing

The splice method does many things at once. It allows you to remove and return a specified number of elements (in a destructive way). It also lets you specify a new set of elements to insert at that exact same position in the array.

You won't end up using this very often but you'll want to keep it in the back of your mind for later anyway.

The basic syntax is:

splice(start index, num removed, insert 1, insert 2...)

And some examples are:

// just removing elements
myArr=[1,2,3,4,5,6];              //=> [1, 2, 3, 4, 5, 6]
myArr.splice(3,2);                //=> [4, 5]
myArr;                            //=> [1, 2, 3, 6]

// removing and inserting elements
myArr=[1,2,3,4,5,6];              //=> [1, 2, 3, 4, 5, 6]
myArr.splice(3,2,"three", "four");//=> [4, 5]
myArr;                            //=> [1, 2, 3, "three", "four", 6]

Comparing Arrays

When you compare two arrays with == or ===, you will NOT get equality even if they contain the same elements:

[1,2,3] == [1,2,3]
//=> false
[1,2,3] === [1,2,3]
//=> false

You'll have to write your own function for this as part of the next assignment.

Iteration

Basic iteration through an array with a for loop and length is simple:

var myArray = [ "hello", "world", "!" ];

// Simple iteration with a `for` loop.
// You will often see the length of the
// array used as the break condition.
for ( var i = 0; i < myArray.length; i = i + 1 ) {
  console.log( myArray[ i ] );
}

The forEach method is more interesting (and often more useful). You pass it a function which takes up to three inputs (though they are all optional):

  1. An element in the array
  2. The index of this element in the array
  3. The array itself

The array will automatically call this function once for each element in the array, passing in said element along with its index.

See this in action below:

// Let's save the array we'll use
myArray = [ 1, 2, 3, 4, 5 ];


// Let's try our `forEach` by passing it a function
// which only takes one argument (the element)
// and prints it.
[1,2,3,4,5].forEach( function(el){ console.log(el); } )
1
2
3
4
5
//=> undefined

Let's make things more interesting. One important thing we mentioned above is that forEach actually passes in three arguments to whatever function you tell it to run. In our example above, we only used one of those arguments. This is a big deal!

In JavaScript, the number of arguments passed isn't terribly important. As you'll see again below, you can choose to use just the first argument, the first two, or all three. To demonstrate this, we'll write a few helper functions (to avoid cluttering up the output later) which take different numbers of arguments and then use them down below:

// First, set up a simple print function which takes
// only the first argument (the element) and prints it
function printEl( el ) {
  console.log( el );
}

// Then create another one which adds in the index
function printElAndIndex( el, index ) {
  console.log( "Index " + index + ": " + el );
}

// Aaaand another helper method to print the array
// (the third argument) for demonstration purposes.
// Note that it is taking all three arguments but
// only using the last one.
function printArray( el, index, array ) {
  console.log(array);
}


// Great! Now let's try our `forEach`!
// This one prints all elements to the console by
// using our helper printing function from above
myArray.forEach( printEl );
1
2
3
4
5
//=> undefined

// Now print BOTH the element AND the index
// by using the printElAndIndex function each time
myArray.forEach( printElAndIndex );
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5
//=> undefined

// Finally, let's use the printArray function with
// each iteration to print the original array, which
// was passed in as the third argument
myArray.forEach( printArray );
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
//=> undefined

Map, Filter, Reduce

Another interesting stop is the more functional like methods that are available on Arrays. The most common examples include map, filter and reduce. But what do these functions have in common? Well, glad you asked! They all return new arrays and do not modify the original source in the process. So let's look at each of them in more detail.

The map method takes a function as an argument which takes up to three inputs (though they are all optional):

  1. An element in the array
  2. The index of this element in the array
  3. The array itself

The array will automatically call this function once for each element in the array, passing in said element along with its index. Already sounds familiar? That's right, it's very similar to forEach. However, for every element in the array, map will return another element (it can be the same, or it can be transformed). Thus this method becomes very useful when we want to apply a certain transformation to all elements inside a collection.

Let's look at an example:

var arr = [1, 2, 3];
var arrTransformed = arr.map(function(element, index, arr) {
  return element + 1;
});
console.log(arrTransformed); // [2, 3, 4]

In the example above we have returned a new array into the variable arrTransformed that is basically equal to arr increased by 1 (that is, every element in arr has been summed up with 1).

Pretty neat, huh?

What about filter? Well, the function signature is that same. However, filter will return a new array containing only those elements for which the callback (argument) method that we pass in return true. So let's see an example.

var arr = [1, 2, 3, 4];
var arrTransformed = arr.filter(function(element, index, arr) {
  return element % 2;
});
console.log(arrTransformed); // [2, 4]

In the example above we have returned a new array into the variable arrTransformed that contains only the even numbers from the initial one.

Last one on the list is reduce. reduce is a bit of a different beast, but we can tame it! The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. The function signature is made out of a callback that executes for each element in the array (similar to map or filter) and an initial value (the accumulator). Let's see an example.

var arr = [1, 2, 3, 4];
var total = arr.reduce(function(sum, value) {
  return sum + value;
}, 0);
console.log(total); // 10

In the example above we take all the values in the original array and reduce them to a final, single value based on the logic that we pass in the callback function. 0 stands for the initial value of the sum.

map, filter, reduce are just some of the many more methods that you have available on Arrays. For a complete list, feel free to study this guide.

Insanity

JavaScript lets you get away with some pretty strange things. For example, you can actually set array indexes to be floats:

// EVIL!
myArr = []
myArr[1.32] = "foo"
myArr[1.32]
//=> "foo"

That's because there aren't "Integers" or "Floats"... they're all just numbers. Though you can get away with doing crazy things like this, these values will not show up during conventional iteration and you should pretend you never saw this.

Wrapping Up

Iteration gets interesting when you start using forEach and passing it a function. This is probably one of the first times you’ve passed a function to another function. A function that takes another function as an argument is called a higher-order function. You'll see this pattern used all the time in JavaScript.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!

Next Lesson: Basic Syntax: Objects