Javascript: Array Fundamentals

An array consists of array elements. Array elements are made up of the array name and then an index number that is contained in square brackets. The individual value within an array is called an array element. Arrays use numbers (called the index numbers) to access those elements. The following example illustrates how arrays use index numbers to access elements:

myArray[0] = "yellow balloon";
myArray[1] = "red balloon";
myArray[2] = "blue balloon";
myArray[3] = "pink balloon";


In this example, the element with the index number of 0 has a value of "yellow balloon". The element with an index number 3 has a value of "pink balloon". Just as with any variable, you can give an array any name that complies with the rules of naming JavaScript variables. By assigning index numbers in arrays, JavaScript gives you the ability to make a single variable name hold a nearly unlimited list of values.

Just so you don't get too carried away, there actually is a limit to the number of elements that you can have in an array, although you're very unlikely to ever reach it. The limit is 4,294,967,295 elements.

In addition to naming requirements (which are the same for any type of variable), arrays have a couple of other rules and special properties that you need to be familiar with:

  • Arrays are zero-indexed
  • Arrays can store any type of data

Arrays are zero indexed

The first element in a JavaScript array always has an index number of 0
What this means for you is that myArray[3] is actually the fourth element in the array.

Zero-based numbering is a frequent cause of bugs and confusion for those new to programming, but once you get used to it, it will become quite natural. You may even discover that there are benefits to it, such as the ability to turn your guitar amp up to the 11th level.

Arrays can store any type of data

Each element in an array can store any of the data types, as well as other arrays. Array elements can also contain functions and JavaScript objects.

While you can store any type of data in an array, you can also store elements that contain different types of data, together, within one array, as shown below.

Storing Different Types of Data in an Array
item[0] = "apple";
item[1] = 4+8;
item[2] = 3;
item[3] = item[2] * item[1];









Javascript: Understanding Arrays

Arrays are a fundamental part of any programming language. In this chapter, you discover what they are, how to use them, and what makes JavaScript arrays distinct from arrays in other programming languages. You work with arrays to create lists, order lists, and add and remove items from lists.

The earlier posts in this blog involve working with variables that are standalone pieces of data, such as: var myName = “Chris”, var firstNumber = “3”, and var how ManyTacos = 8. There are often times in programming (and in life) where you want to store related data under a single name.

For example, consider the following types of lists:
  • A list of your favorite artists
  • A program that selects and displays a different quote from a list of quotes each time its run
  • A holiday card mailing list
  • A list of your top music albums of the year
  • A list of all your family and friends' birthdays
  • A shopping list
  • A to-do list
  • A list of New Year’s resolutions

Using single-value variables , you would need to create and keep track of multiple variables in order to accomplish any of these tasks. Here is an example of a list created using single-value variables:

var artist1 = "Alphonse Mucha";
var artist2 = "Chiara Bautista";
var artist3 = "Claude Monet";
var artist4 = "Sandro Botticelli";
var artist5 = "Andy Warhol";
var artist6 = "Wassily Kadinski";
var artist7 = "Vincent Van Gough";
var artist8 = "Paul Klee";
var artist9 = "William Blake";
var artist10 = "Egon Schiele";
var artist11 = "Salvador Dali";
var artist12 = "Paul Cezanne";
var artist13 = "Diego Rivera";
var artist14 = "Pablo Picasso";


This approach could work in the short term, but you’d quickly run into difficulties. For example, what if you wanted to sort the list alphabetically and move artists into the correct variable names based on their position in the alphabetical sort? You’d need to first move Mucha out of the artist1 variable (maybe into a temporary holding variable) and then move Bautista into the artist1 variable. The artist2 spot would then be free for Blake, but don’t forget that Mucha is still in that temporary slot! Blake’s removal from artist9 frees that up for you to move someone else into the temporary variable, and so on. Creating a list in this way quickly becomes complicated and confusing.

Fortunately, JavaScript (and every other programming language we know of) supports the creation of variables containing multiple values, called arrays.

Arrays are a way to store groups of related data inside of a single variable. With arrays, you can create lists containing any mix of string values, numbers, Boolean values, objects, functions, any other type of data, and even other arrays!


Javascript: Data Types

Number data type
Numbers in JavaScript are stored as 64-bit, floating point values. What this means, in English, is that numbers can range from 5e-324 (that’s -5 followed by 324 zeros) to 1.7976931348623157e+308 (move the decimal 308 spots to the right to see this giant number). Any number may have decimal points or not. Unlike most programming languages, JavaScript doesn’t have separate data types for integers (positive or negative numbers without a fractional part) and floating points (decimals).

Just how big is the biggest number JavaScript can use? Here it is, written out without scientific notation:

179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

When you declare a number variable, you compile it from all of the following elements:

  • The var keyword
  • The name you want to give your variable
  • The assignment operator
  • A number (or even an equation that resolves to a number
  • A semicolon

Here are some examples of valid number variables declarations:
var numberOfDucks = 4;
var populationOfSpain = 47200000;
var howManyTacos = 8;


Number functions
JavaScript includes a built-in Number function for converting values to numbers. To use the Number function, simply put the value (or a variable holding the value) that you want to convert to a number between the parentheses after the Number function.

The Number function produces four kinds of output:

  • Numbers that are formatted as text strings are converted to numbers that can be used for calculations, like this:
    Number("42") // returns the number 42
  • Text strings that can’t be converted to numbers return the value NaN, like this:
    Number("eggs") // returns NaN
  • The Boolean value true returns the number 1, like this:
    Number(true) // returns 1
  • The Boolean value false returns the number 0, like this:
    Number(false) // returns 0

parseInt() function
To JavaScript, all numbers are actually floating point numbers. However, you can use the parseInt() function to tell JavaScript to consider only the nonfractional part of the number (the integer), discarding everything after the decimal point.

parseInt(100.33); // returns 100

parseFloat(); function
You can use parseFloat() to specifically tell JavaScript to treat a number as a float. Or, you can even use it to convert a string to a number. For example:

parseFloat("10"); // returns 10
parseFloat(100.00); //returns 100.00
parseFloat("10"); //returns 10




String data type

Strings can be made up of any characters:
  • Letter
  • Number
  • Punctuation (such as commas and periods)
  • Special characters that can be written using a backslash followed by character
Some characters, such as quotes, have special meaning in JavaScript or require a special combination of characters, such as a tab or new line, to represent inside of a string.

Code
Outputs
\'
single quote
\"
double quote
\\
backslash
\n
new line
\r
carriage return
\t
tab
\b
backspace
\f
form feed
You create a string variable by enclosing it in single or double quotes, like this:

var myString = "Hi, I'm a string.";

It doesn’t actually matter whether you use single or double quotes, as long as the beginning and ending quotes surrounding the string match up.

If you surround your string with single quotes, you can actually use double quotes within that string without a problem. The same goes for if you surround your strings with double quotes; you can use single quotes within the string without a problem.

However, if you create a string and surround it with one type of quote, you can’t use that type of quote inside the string, or the JavaScript parser will think you mean to end the string and will generate an error.

Escaping quotes
The solution to the problem of not being able to include quotes inside of a string surrounded with that type of quotes is to preface the quotes with a \. Adding a backslash before a quote is called escaping the quotes.

String functions
JavaScript includes many helpful functions for working with and converting strings.

Here’s a list of the most frequently used built-in string functions:

  • charAt( ) produces the character at a specified position. Note that the counting of characters starts with 0:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.charAt(3));
    // returns a

  • concat() combines one or more strings and returns the incorporated string:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.concat(‘ We love JavaScript!’));
    // returns JavaScript is Fun! We love JavaScript!

  • indexOf () searches and returns the position of the first occurrence of the searched character or substring within the string:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.indexOf(‘Fun’);
    // returns 14

  • split() splits strings into an array of substrings:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.split(‘F’));
    // returns ["JavaScript is ", "un!"]

  • substr() extracts a portion of a string beginning at "start" through a specified length:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.substr(2,5));
    // returns vaScr

  • substring() extracts the characters within a string between two specified positions:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.substring(2,5));
    // returns Vas

  • toLowerCase() produces the string with all of its characters converted to lowercase:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.toLowerCase());
    // returns javascript is fun!

  • toUpperCase() produces the string with all of its characters converted to uppercase:
    var watzThisString = ‘JavaScript is Fun!’;
    console.log (watzThisString.toUpperCase());
    // returns JAVASCRIPT IS FUN!


Boolean data type

Boolean variables store one of two possible values: either true or false.

Boolean variables are often used for storing the results of comparisons. You can find out the Boolean value of a comparison or convert any value in JavaScript into a Boolean value by using the Boolean() function. For example:

var isItGreater = Boolean (3 > 20);
alert (isItGreater); // returns false

var areTheySame = Boolean ("tiger" === "Tiger");
alert (areTheySame); // returns false


The result of converting a value in JavaScript into a Boolean value using the Boolean() function depends on the value:

The result of converting a value in JavaScript into a Boolean value using the Boolean() function depends on the value:

  • In JavaScript, the following values always evaluate to a Boolean false value:
    • NaN
    • undefined
    • 0 (numeric value zero)
    • -0
    • "" (empty string)
    • false
  • Anything that is not one of the preceding values evaluates to a Boolean true. For example:
    • 74
    • "Eva"
    • "10"
    • "NaN"
 Boolean values are written without quotes around them, like this:

var myVar = true
On the other hand, var myVar = “true” creates a string variable.



 NaN data type

NaN stands for Not a Number. It’s the result that you get when you try to do math with a string, or when a calculation fails or can’t be done. For example, it’s impossible to calculate the square root of a negative number. Trying to do so will result in NaN.

undefined data type

Even if you create a variable in JavaScript and don’t specifically give it a value, it still has a default value. This value is "undefined".