Skip to content

Various small fixes on the JavaScript 101 Arrays page. #352

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 56 additions & 46 deletions page/javascript-101/arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ source: http://jqfundamentals.com/legacy
attribution:
- jQuery Fundamentals
---

Arrays are zero-indexed, ordered lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.

To create an array, either use the object constructor or the literal declaration, by assigning the variable a list of values after the declaration.

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

// Literal declaration, the preferred way.
var myArray2 = [ "hello", "world" ];
```
Expand All @@ -21,23 +23,25 @@ The literal declaration is generally preferred. See the [Google Coding Guideline
If the values are unknown, it is also possible to declare an empty array, and add elements either through functions or through accessing by index:

```
// Creating empty arrays and adding values
// Creating empty arrays and adding values.

var myArray = [];

// adds "hello" on index 0
// Adds "hello" on index 0
myArray.push( "hello" );

// adds "world" on index 1
// Adds "world" on index 1
myArray.push( "world" );

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

`.push()` is a function that adds an element on the end of the array and expands the array respectively. You also can directly add items by index. Missing indices will be filled with `undefined`.

```
// Leaving indices
// Leaving indices.

var myArray = [];

myArray[ 0 ] = "hello";
Expand All @@ -50,10 +54,11 @@ console.log( myArray ); // [ "hello", "world", undefined, "!" ];
If the size of the array is unknown, `.push()` is far more safe. You can both access and assign values to array items with the index.

```
// Accessing array items by index
// Accessing array items by index.

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

console.log( myArray[2] ); // "!"
console.log( myArray[ 2 ] ); // "!"
```

## Array Methods and Properties
Expand All @@ -63,7 +68,8 @@ console.log( myArray[2] ); // "!"
The `.length` property is used to determine the amount of items in an array.

```
// Length of an array
// Length of an array.

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

console.log( myArray.length ); // 3
Expand All @@ -72,22 +78,28 @@ console.log( myArray.length ); // 3
You will need the `.length` property for looping through an array:

```
// For loops and arrays - a classic
// For loops and arrays - a classic.

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

for ( var i = 0; i < myArray.length; i = i + 1 ) {
console.log( myArray[i] );

console.log( myArray[ i ] );

}
```

Except when using `for`/`in` loops:

```
// For loops and arrays - alternate method
// For loops and arrays - alternate method.

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

for ( var i in myArray ) {

console.log( myArray[ i ] );

}
```

Expand All @@ -96,31 +108,29 @@ for ( var i in myArray ) {
Concatenate two or more arrays with `.concat()`:

```
// Concatenating Arrays
var myArray = [ 2, 3, 4 ];
var myOtherArray = [ 5, 6, 7 ];

// [ 2, 3, 4, 5, 6, 7 ]
var wholeArray = myArray.concat( myOtherArray );
var wholeArray = myArray.concat( myOtherArray ); // [ 2, 3, 4, 5, 6, 7 ]
```

### .join()

`.join()` creates a string representation of an array by joining all of its elements using a separator string. If no separator is supplied (e.g. `.join()` is called without arguments) the array will be joined using a comma:
`.join()` creates a string representation of an array by joining all of its elements using a separator string. If no separator is supplied (e.g. `.join()` is called without arguments) the array will be joined using a comma.

```
// Joining elements
// Joining elements.

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

// The default separator is a comma
// The default separator is a comma.
console.log( myArray.join() ); // "hello,world,!"

// Any string can be used as separator...
console.log( myArray.join(" ") ); // "hello world !";
console.log( myArray.join("!!") ); // "hello!!world!!!";
console.log( myArray.join( " " ) ); // "hello world !";
console.log( myArray.join( "!!" ) ); // "hello!!world!!!";

// ...including an empty one
console.log( myArray.join("") ); // "helloworld!"
// ...including an empty one.
console.log( myArray.join( "" ) ); // "helloworld!"

```

Expand All @@ -129,7 +139,8 @@ console.log( myArray.join("") ); // "helloworld!"
`.pop()` removes the last element of an array. It is the opposite method of `.push()`:

```
// pushing and popping
// Pushing and popping.

var myArray = [];

myArray.push( 0 ); // [ 0 ]
Expand All @@ -143,19 +154,17 @@ myArray.pop(); // [ 0 , 2 ]
As the name suggests, the elements of the array are in reverse order after calling this method:

```
// reverse
var myArray = [ "world" , "hello" ];

// [ "hello", "world" ]
myArray.reverse();
myArray.reverse(); // [ "hello", "world" ]
```

### .shift()

Removes the first element of an array. With `.push()` and `.shift()`, you can recreate the method of a [queue](http://en.wikipedia.org/wiki/Queue_(data_structure)):
Removes the first element of an array. With `.push()` and `.shift()`, you can recreate the method of a [queue](http://en.wikipedia.org/wiki/Queue_(abstract_data_type%29):

```
// queue with shift() and push()
// Queue with shift() and push()

var myArray = [];

myArray.push( 0 ); // [ 0 ]
Expand All @@ -169,7 +178,8 @@ myArray.shift(); // [ 2 , 7 ]
Extracts a part of the array and returns that part in a new array. This method takes one parameter, which is the starting index:

```
// slicing
// Slicing.

var myArray = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
var newArray = myArray.slice( 3 );

Expand All @@ -182,18 +192,16 @@ console.log( newArray ); // [ 4, 5, 6, 7, 8 ]
Removes a certain amount of elements and adds new ones at the given index. It takes at least three parameters:

```
// splice method
myArray.splice( index, length, values, ... );
```

* *Index* - The starting index.
* *Length* - The number of elements to remove.
* *Values* - The values to be inserted at the Index position.
* *Index* The starting index.
* *Length* The number of elements to remove.
* *Values* The values to be inserted at the index position.

For example:

```
// splice example
var myArray = [ 0, 7, 8, 5 ];
myArray.splice( 1, 2, 1, 2, 3, 4 );

Expand All @@ -205,14 +213,16 @@ console.log( myArray ); // [ 0, 1, 2, 3, 4, 5 ]
Sorts an array. It takes one parameter, which is a comparing function. If this function is not given, the array is sorted ascending:

```
// sorting without comparing function
// Sorting without comparing function.

var myArray = [ 3, 4, 6, 1 ];

myArray.sort(); // 1, 3, 4, 6
```

```
// sorting with comparing function
// Sorting with comparing function.

function descending( a, b ) {
return b - a;
}
Expand All @@ -222,14 +232,13 @@ var myArray = [ 3, 4, 6, 1 ];
myArray.sort( descending ); // [ 6, 4, 3, 1 ]
```

The return value of descending (for this example) is important. If the return value is less than zero, the index of a is before b, and if it is greater than zero it's vice-versa. If the return value is zero, the elements index is equal.
The return value of descending (for this example) is important. If the return value is less than zero, the index of `a` is before `b`, and if it is greater than zero it's vice-versa. If the return value is zero, the elements' index is equal.

### .unshift()

Inserts an element at the first position of the array:

```
// unshift
var myArray = [];

myArray.unshift( 0 ); // [ 0 ]
Expand All @@ -243,14 +252,15 @@ In modern browsers it is possible to traverse through arrays with a `.forEach()`

The function takes up to three arguments:

* *Element* - The element itself.
* *Index* - The index of this element in the array.
* *Array* - The array itself.
* *Element* The element itself.
* *Index* The index of this element in the array.
* *Array* The array itself.

All of these are optional, but you will need at least the "Element" parameter in most cases.
All of these are optional, but you will need at least the *Element* parameter in most cases.

```
// native forEach
// Native .forEach()

function printElement( elem ) {
console.log( elem );
}
Expand All @@ -265,10 +275,10 @@ function negateElement( elem, index, array ) {

myArray = [ 1, 2, 3, 4, 5 ];

// prints all elements to the console
// Prints all elements to the console.
myArray.forEach( printElement );

// prints "Index 0: 1" "Index 1: 2" "Index 2: 3" ...
// Prints "Index 0: 1", "Index 1: 2", "Index 2: 3", ...
myArray.forEach( printElementAndIndex );

// myArray is now [ -1, -2, -3, -4, -5 ]
Expand Down