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".




Javascript: Variables Naming

Variable names can start with the following characters:

  • Upper- or lowercase letter
  • An underscore (_)
  • A dollar sign ($)
 Although you can use an underscore or dollar sign to start a variable, it’s best to begin with a letter. Unexpected characters can often cause your code to look confusing and difficult to read, especially if you are new to JavaScript coding.

After the first character, you can use any letter or number in your variable name, and it can be any length. JavaScript variables cannot contain spaces, mathematical operators, or punctuation (other than the underscore).

Always remember that JavaScript is case-sensitive. A variable named myname is not the same variable as Myname or myName.

Variable names are actually identifiers; the best thing you can do is to name a variable something precise and relevant. This naming convention may sometimes result in very long names, but as a rule, a longer name that accurately represents the variable is more useful than a shorter name that is vague.

Javascript: Understanding Global and Local Scope

How and where you declare a variable determines how and where your program can make use of that variable. This concept is called variable scope. JavaScript has two types of scope:

  • Global variables can be used anywhere inside of a program.
  • Local (function) variables are variables that you create inside of a protected program within a program, called a function.
In below example, the programmer wants to have a variable called movie that is global, and a separate variable with the same name that is only valid within the function called showBadMovie. This is a perfectly normal thing to do, and under normal circumstances, the movie variable inside the function wouldn’t affect the global variable. However, if you forget to use the var keyword when declaring the movie variable inside the function, bad things happen.

var movie = "The Godfather";

function showGoodMovie () {
  alert (movie + " is a good movie!");
}

function showBadMovie () {
  movie = "Speed 2: Cruise Control";
  alert (movie + " is a bad movie!");
}


Notice that the var keyword is missing from before the movie variable in showBadMovie(). JavaScript assumes that you want to override the global movie variable, rather than create a local function variable. The results are positively disastrous!

showGoodMovie(); // pops up "The Godfather is a good movie!"

showBadMovie(); // pops up "Speed 2: Cruise Control is a bad movie!"


/* Oh no! The global variable is now Speed 2: Cruise Control, not the good movie name anymore! */

showGoodMovie(); // pops up "Speed 2: Cruise Control is a good movie!"

javascript: Declaring Variables

Declaring a variable is the technical term that’s used to describe the process of first creating a variable in a program. You may also hear it called initialization. Creating a variable, declaring a variable, and initializing a variable all refer to the same thing.

Variables in JavaScript can be created in one of two ways:

Using a var keyword:
var myName;

A variable created using a var keyword will have an initial value of undefined unless you give it a value when you create it, such as
var myName = "Chris";

Without a var keyword
myName = "Chris";

When you create a variable without a var keyword, it becomes a global variable. (In order to understand what a global variable means, see the next post.)

JavaScript: Understanding Variables

Variables are representative names in a program. Just as x may stand for some as-yet-unknown value in algebra, or x may mark the spot where the treasure is buried on a pirate’s map, variables are used in programming to represent something else.

You can think about variables as containers that contain data. You can give these containers names, and later you can recall and change the data in a variable by using its name.

Without variables, every computer program would have only one purpose. For example, the following one-line program doesn’t use variables:

alert(3 + 7);
 
Its purpose is to add together the numbers 3 and 7 and to print out the result in a browser popup window.

The program isn’t of much use, however (unless you happen to need to recall the sum of 3 and 7 on a regular basis). With variables, you can make a general purpose program that can add together any two numbers and print out the result, like the following example:

var firstNumber = 3;
var secondNumber = 7;
var total = Number(firstNumber) + Number(secondNumber);
alert (total);

 
Taken a step further, you can expand this program to ask the user for two numbers and then add them together, like the following example:

var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");
var total = Number(firstNumber) + Number(secondNumber);
alert (total);

Reserved words in JavaScript

Certain words in JavaScript are reserved, which means you can’t use them as variables, identifiers, or constant names within your program because doing so will cause the code to have unexpected results, such as errors. For example, you’ve already seen the reserved word var in previous examples. Using the word var to do anything but declare a variable can cause an error or other unexpected behavior, depending on the browser. Consider this statement:

// Don't do this!
var var = 4;


The code example won’t result in a direct error to a browser, but it also won’t work as you intended, possibly causing confusion when a variable’s value isn’t what you expect.
The following table includes the words that are currently reserved by the ECMA-262 edition 5.1 specification:

break, delete, if, this, while, case, do, in, throw, with, catch, else, instanceof, try, continue, finally, new, typeof, debugger, for, return, var, default, function, switch, void

Several other words (shown in the following table) are reserved for future use and therefore
shouldn’t be used in your programs:

class enum extends super
const export import


The following table shows the words that are reserved for the future when in strict mode:

implements let private public yield
interface package protected static

JavaScript statements

What’s in a statement?
“JavaScript is more than you might think,” a JavaScript statement, or expression,
is a collection of tokens of various categories including keywords, literals, separators, operators,
and identifiers that are put together to create something that makes sense to the JavaScript interpreter.
A statement usually ends with a semicolon, except in special cases like loop constructors such
as if, while, and for,”
Here are some examples of basic statements in JavaScript:

var x = 4;
var y = x * 4;
alert("Hello");


The two types of JavaScript statements

JavaScript statements come in two basic forms, simple and compound. I won’t spend a lot of time discussing statements because you don’t really need to know much about them. However, you should know the difference between simple and compound statements. A simple statement is just what you’d expect—it’s simple, like so:

x = 4;

A compound statement combines multiple levels of logic. An if/then/else conditional such as the one given here provides a good example of this:

if (something == 1) {
// some code here
} else {
// some other code here
}

Placing JavaScript correctly

JavaScript can be placed in a couple of locations within a Hypertext Markup Language (HTML) page: in the <HEAD> </HEAD> section or between the <BODY> and </BODY> tags. The most common location for JavaScript has traditionally been between the <HEAD> and </HEAD> tags near the top of the page. However, placing the <SCRIPT> stanza within the <BODY> section is becoming more common. Be sure to declare what type of script you’re using. Although other script types can be used, because this is a JavaScript book, I’ll declare the following within the opening <SCRIPT> tag:

<script type="text/javascript">

One important issue to note when you use JavaScript relates to pages declared as Extensible Hypertext Markup Language (XHTML). Therefore, JavaScript used within strict XHTML should be declared as follows:

<script type="text/javascript">
<![CDATA[
//JavaScript goes here
]]>
</script>


Older browsers might not parse the CDATA section correctly. This problem can be worked around by placing the CDATA opening and closing lines within JavaScript comments, like this:

<script type="text/javascript">
//<![CDATA[
//JavaScript goes here
//]]>
</script>


When you place the actual JavaScript code in a separate file, you don’t need to use this ugly CDATA section at all. You’ll probably
discover that for anything but the smallest scripts, defining your JavaScript in separate files—usually
with the file extension .js—and then linking to those scripts within the page, is desirable. Here’s a reminder of how you link to a file using the src attribute of the
<SCRIPT> tag:

<script type="text/javascript" src="myscript.js"></script>

Getting started

Case sensitivity
JavaScript is case sensitive. You must be aware of this when naming variables and using the language
keywords. A variable named remote is not the same as a variable named Remote or one named
REMOTE. Similarly, the loop control keyword while is perfectly valid, but naming it WHILE or While will result in an error.
Keywords are lowercase, but variables can be any mix of case that you’d like. As long you are
consistent with the case, you can create any combination you want. For example, all the following
examples are perfectly legal variable names in JavaScript:
buttonOne
txt1
a
C

White space
For the most part, JavaScript ignores white space, which is the space between statements in JavaScript.
You can use spaces, indenting, or whatever coding standards you prefer to make the JavaScript more
readable. However, there are some exceptions to this rule. Some keywords, such as return, can be
misinterpreted by the JavaScript interpreter when they’re included on a line by themselves.
Making programs more readable is a good enough reason to include white space. Consider the
following code sample. It includes minimal white space and indenting.

function cubeme(incomingNum) {
if (incomingNum == 1) {
return "What are you doing?";
} else {
return Math.pow(incomingNum,3);
}
}
var theNum = 2;
var finalNum = cubeme(theNum);
if (isNaN(finalNum)) {
alert("You should know that 1 to any power is 1.");
} else {
alert("When cubed, " + theNum + " is " + finalNum);
}
Now consider the same code with indenting.
 

function cubeme(incomingNum) {
if (incomingNum == 1) {
return "What are you doing?";
} else {
return Math.pow(incomingNum,3);
}
}
var theNum = 2;
var finalNum = cubeme(theNum);
if (isNaN(finalNum)) {
alert("You should know that 1 to any power is 1.");

} else {
alert("When cubed, " + theNum + " is " + finalNum);
}


The second code sample performs just like the first, but it’s easier to read and follow—at least it appears so to me! I find that it takes a short amount of time to actually write code but several years to work with it. When I visit the code a year later, I’m much happier when I’ve made the code more readable and easier to follow.

Comments
Speaking of creating more readable code and maintaining that code over the long term: Comments are your friends. Code that seems blatantly obvious now won’t be nearly so obvious the next time you look at it, especially if a lot of time has passed since you wrote it. Comments can be placed into JavaScript code in two ways: multiline and single-line.
A multiline comment in JavaScript will look familiar to you if you’ve coded in the C programming language. A multiline comment begins and ends with /* and */, respectively, as the following code example shows:

/* This is a multiline comment in JavaScript
It is just like a C-style comment insofar as it can
span multiple lines before being closed. */
A single-line comment begins with two front slashes (//) and has no end requirement because it spans only a single line. An example is shown here:
// Here is a single-line comment.
Using multiple single-line comments is perfectly valid, and I use them for short comment blocks rather than using the multiline comment style previously shown. For example, look at this block of code:
// Here is another comment block.
// This one uses multiple lines.
// Each line must be preceded with two slashes.


Semicolons
Semicolons are used to delineate expressions in JavaScript. Technically, semicolons are not required
for most statements and expressions. However, the subtle problems that you can encounter when
you don’t use semicolons add unnecessary errors and hence unnecessary debugging time. In some
instances, the JavaScript interpreter inserts a semicolon when you might not have wanted one at all.
For example, consider this statement:
return
(varName);
In all likelihood, you wanted to write:
return(varName);
But JavaScript, acting on its own, inserts a semicolon after the return statement, making the code
appear like this to the JavaScript interpreter:
return;
(varName);
This code won’t work; the interpreter will misunderstand your intentions. If you used this code
in a function, it would return undefined to the caller, which is unlikely to be what you want. This is
an example where free use of white space is not allowed—you can’t successfully use line breaks
(explained in the next section) to separate the return keyword from the value that it’s supposed to
return.

But you definitely shouldn’t use semicolons in one instance: when using loops and conditionals.
Consider this bit of code:
if (a == 4)
{
// code goes here
}

In this case, you wouldn’t use a semicolon at the end of the if statement. The reason is that the
statement or block of statements in opening and closing braces that follows a conditional is part of
the conditional statement—in this case, the if statement. A semicolon marks the end of the if statement,
and if improperly placed, dissociates the first part of the if statement from the rest of it. For
example, the following code is wrong (the code within the braces will execute regardless of whether a
equals 4):
if (a == 4);
{
// code goes here
}


Line breaks
Related closely to white space and even to semicolons in JavaScript are line breaks, sometimes called carriage returns. Known in the official ECMA-262 standard as “Line Terminators,” these characters separate one line of code from the next. Like semicolons, the placement of line breaks matters. As you saw from the example in the previous section, placing a line break in the wrong position can result in unforeseen behavior or errors.
Not surprisingly, the most common use of line breaks is to separate individual lines of code for readability. You can also improve readability of particularly long lines of code by separating them with line breaks. However, when doing so, be aware of issues like the one illustrated by the return statement cited earlier, in which an extra line break can have unwanted effects on the meaning of the code.