jQuery and JavaScript Phrasebook (2014)

2. Using the JavaScript Language

The phrases in this chapter focus on various ins and outs of the JavaScript language. You need to know these to be able to fully utilize the full capabilities that jQuery and JavaScript provide in the HTML stack.

JavaScript Syntax

As a programming language, JavaScript, and consequently jQuery since it is based on JavaScript, requires a specific syntax. This section gives you a quick primer on the JavaScript syntax before going into the language details.

You should be familiar with the following rules regarding JavaScript syntax:

Image All JavaScript statements end with a semicolon.

Image Statements execute in the order they appear in the script.

Image Blocks of code are defined using {CODE_BLOCK} brackets.

Image Expressions bound in () brackets are evaluated before they’re applied to the rest of the statement.

Image JavaScript is case sensitive.

Image To break a code line in the middle of a string, \ must be the last character on the line.

Image Strings in JavaScript must be enclosed in either single ('string') or double ("string") quotes.

Image When adding a string to a number, the resulting value is a string.

Image Variables must begin with a letter, $, or _.

Defining and Accessing Data

One of the most important aspects of JavaScript is the ability to define variables that represent different forms of data, from individual numbers and strings to complex objects with properties and methods to arrays containing several items. Once data has been defined, you can use and reuse it for a variety of purposes. This section provides phrases that help you create the various data structures that you will need to use in JavaScript.

Defining and Accessing Variables

  var x = y = 5;
  var z = 10;
  var results = "x + y + z = " + (x+y+z);
  var s1 = "jQuery";
  var s2 = "JavaScript"
  var s3 = s1 + " & " + s2;

JavaScript makes it easy to define variables. Variables are assigned using var name = value; syntax. The var keyword tells JavaScript that this is a new variable name. Once the variable has been assigned a value, you can access it using the variable name. You can define multiple variables on a single line using var name1 = name2 = value; syntax.

When you assign a variable to an expression, such as x + y + z, the expression is evaluated before assigning the variable a value. The following code snippet shows you how to define and access different variables.

  var x = y = 5;
  var z = 10;
  var results = "x + y + z = " + (x+y+z);
  var s1 = "jQuery";
  var s2 = "JavaScript"
  var s3 = s1 + " & " + s2;


x + y + z = 20
jQuery & JavaScript

Output from ch0201.html

Creating Arrays

  var x = y = 5;
  var z = 10;
  var results = "x + y + z = " + (x+y+z);
  var s1 = "jQuery";
  var s2 = "JavaScript"
  var s3 = s1 + " & " + s2;

You can create arrays in a few different ways. You can create them in the definition using [] brackets, such as var arr=[1,2,3]. You can also create a new array object and add items to it using the push() method. You can access items in the array using the arr[index] method. The following code snippet shows an example of creating an array in each of these ways.

  var weekdays = ["Mon", "Tue", "Wed", "thur", "Fri"];
  var weekend = new Array();
  document.write(weekdays.toString() + "<br>");
  document.write(weekend[0] + ", " + weekend[0]);



Output from ch0202.html

Creating Objects

  var obj1 = {name:"Brad", title:"Author", "last-name":"Dayley" };
  var obj2 = new Object();
  obj2.name = "Frodo";
  obj2.title = "Hobbit";
  obj2["last-name"] = "Baggins";

You can create objects in the definition using {property:value, ..} syntax, such as var obj={name:"Brad", title:"Author"};. You can also create a new object and add properties to it using standard dot syntax.

The following code snippet shows an example of creating an array in each of these ways.

  var obj1 = {name:"Brad", title:"Author", "last-name":"Dayley" };
  var obj2 = new Object();
  obj2.name = "Frodo";
  obj2.title = "Hobbit";
  obj2["last-name"] = "Baggins";
  document.write(obj1.name + " " + obj1["last-name"] + ", " + obj1.title + "<br>");
  document.write(obj2.name + " " + obj2["last-name"] + ", " + obj2.title);


Brad Dayley, Author
Frodo Baggins, Hobbit

Output from ch0203.html

Defining Functions

  function add(a, b){
    return a + b;
  var result1 = add(5, 20);

You need to be familiar with creating and using functions in JavaScript. Functions are defined using the following syntax:

function function_name(arguments){function_block}

You can specify any number of arguments, and because JavaScript is loosely typed, you can pass in different object types each time you call the function. To call the function, simply reference it by name and pass in the desired arguments enclosed in () brackets. The code in the functionblock is then executed. You can use the return keyword to return a value from the function call.

The following code snippet shows examples of defining and calling functions:

  function add(a, b){
    return a + b;
  var result1 = add(5, 20);
  var result2 = add("Java", "Script")
  document.write(result1 + "<br>");



Output from ch0204.html

Manipulating Strings

Strings are one of the most important data structures in JavaScript. Strings represent data that is conveyed to the user on the web page, whether it is a paragraph element, the name on a button, a menu label, or a figure caption. Strings are also used in the background to define locations, filenames, and a variety of other values used in web elements.

There are several special characters to define values that cannot be represented otherwise, such as new lines and tabs. Table 2.1 lists the special characters in JavaScript strings.


Table 2.1 String Object Special Character

Getting the Length of a String

var s = "One Ring";
s.length; //returns 8
var s2 = "To Rule\nThem All";
s2.length; //returns 16 because \n is only 1 character

String objects have a length attribute that contains the number of characters in the string. This includes the number of special characters as well, such as \t and \n. To get the length of the string, simply use the .length attribute on the string object.

Finding What Character Is at a Specific Location in a String

var s = "In The Darkness Bind Them";
s.charAt(7); //returns 'D'
s[7]; // also returns 'D'

String objects provide the charAt(offset), which returns the character contained at the offset specified. Also, strings in JavaScript are basically arrays of characters, so you can get the character at a specific offset using stringName[offset]. Keep in mind that the offsets are always zero based, so their first character is at offset 0.

Converting Numbers to Strings

var n=16;
var a = n.toString();  //a = 16
var b = n.toString(16); //b = 10

To convert a number to a string in JavaScript, create a variable with the numerical value if you don’t already have one and then call .toString(radix) on the number. The optional radix parameter specifies the base to use when converting the number. You can specify base 2 up to base36.

Converting Strings to Numbers

new Number("16");   //returns 16
new Number("0x20"); //returns 32
new Number("32.8"); //returns 32.8

To convert numerical-based strings into a number, create a new number object. JavaScript automatically detects whether the string is a number (even hex number with 0x## formatting) and create a new number object. If the string is not a valid number format, a NaN object is returned.

Combining Strings

var str1="jQuery";
var str2=" & ";
var str3="JavaScript";
var str4 = str1.concat(str2, str3); //str5 = "jQuery & JavaScript"
var str5 = str4 + " Phrasebook";    //str5 = "jQuery & JavaScript Phrasebook"

You can combine multiple strings using the .concat(str, str, ...) method. Or you can just use the str + str + str . . . method.

Changing String Case

var s1 = "jQuery and JavaScript";
var s2  = s1.toLowerCase();  //s2 = "jquery & javascript"
var s3  = s1.toUpperCase(); //s3 = "JQUERY & JAVASCRIPT"

Strings have built-in functions to change the case. The .toLowerCase() method returns a lowercase version of the string. The .toUpperCase() method returns an uppercase version of the string.

Splicing Strings

var s1 = "The play's the thing";
var s2 = s1.splice(4,8); // s2 = "play"

You can carve a string into substrings using .splice(start, end) by specifying the starting index and the ending index. The section of the string starting with the character at the index specified by start and ending with the character just before end index is returned. All indexes are zero based.

Splitting Strings

var s1 = "on-the-way-to-the/forum";
var arr = s1.split("-"); // arr = ["on", "the", "way", "to", "the","forum"];

To split a string into chunks using a specific delimiter, use the .split(separator [, limit]). The separator defines where to split the string and is not included in the results. The limit specifies the number of items to return before stopping. An array of the split portions of the string is returned.

Checking to See If a String Contains a Substring

var s1 = "I think therefore I am";
var a = s1.indexOf("think");     // a = 2
var b = s1.indexOf("thought"); // b = -1

The simplest way to check to see if one string is a substring of another is to use .indexOf(substring) on the main string. This function returns an index of the location of the first occurrence, or –1 if the substring is not found.

Finding and Replacing Substrings Regardless of Case

var s1 = "jQuery, sometimes JQuery or JQUERY";
var s2 = s1.replace(/jQuery/gi, "jQuery");
//s2 is now "jQuery, sometimes jQuery or jQuery"

The best way to find and replace substrings while ignoring case is to use a regular expression in the .replace() method. If you are not familiar with them, I’d suggest you at least look into them. They can use complex formulas for finding matches in strings. For now, I’ll just show you a simple expression.

As an example, to find all instances of the term jQuery when you may not know the case specified in the string, you would define the following regular expression. The g character specifies a global search (meaning not to stop at the first instance). The i character specifies to ignore case.


Manipulating Arrays

One of the most useful data structures in JavaScript is arrays. Arrays are collections of items that can be of any type. You have already seen how to create and access the individual items. This section contains phrases designed to show you how to manipulate the arrays by combining them, slicing them, searching for items, and more.

Combining Arrays

var fruits = ["banana", "apple", "orange"];
var veggies = ["broccoli", "carrots", "spinach"];
var grains = ["wheat", "oats"];
var food = grains.concat(fruits, veggies);
//food = ["wheat","oats","broccoli","carrots", "spinach","banana","apple","orange"]

You can combine multiple arrays using the .concat(arr, arr, ...) method. This returns a new array object with the array elements combined inside.

Splicing Arrays

var week = ["sun", "Mon", "Tue", "Wed", "thur", "Fri", "sat"];
var weekdays = week.slice(1,6);

You can carve arrays the same way you can strings by using the .splice(start, end) method and specifying the starting index and the ending index. The items in the array beginning with the start index until the item just before the end index are returned in a new array object. All indexes are zero based.

Detecting Whether an Array Contains an Item

var food = ["broccoli", "carrots", "spinach"];
var a = food.indexOf("spinach");     // a = 2
var b = food.indexOf("pizza"); // b = -1

The simplest way to check whether an item already exists in an array is to use the .indexOf(item). If the item is found, the index of the first instance is returned; otherwise, –1 is returned.

Removing Items from the Array

var week = ["sun", "Mon", "Tue", "Wed", "thur", "Fri", "sat"];
var weekdays = week.splice(1,5);
var day = week.pop();
// weekdays= ["Mon", "Tue", "Wed", "thur", "Fri"]
// day = "sat"
// week = ["sun", "Mon", "Tue", "Wed", "thur", "Fri"];

You can remove the last item in the array using pop(). If you want to remove items in the middle of the array, you need to use splice(index, count), where index is the index to begin removing items from and count is the number of items to remove.

Creating a Tab-Separated String from an Array

var weekdays= ["Mon", "Tue", "Wed", "thur", "Fri"]
var weekStr = weekdays.join("\t");
// weekStr = "Mon\tTue\tWed\tthur\tFri"

The .join(separator) method allows you to combine an array into a string. The optional separator argument specifies the character or string to place between each item in the newly created string.

Sorting Arrays

arr1.sort(function(a,b){return a-b;});
arr1.sort(function(a,b){return Math.abs(a)-Math.abs(b);});

JavaScript provides a nice interface to sort arrays. The array object has a sort(function) method. The sort() method sorts the elements of the array in alphabetical order, converting elements to strings if possible, which is a problem for numerical arrays. You can specify your own sort function that accepts two elements and returns the following:

Image true or a positive number if the first value should be sorted higher

Image 0 if they are equal

Image false or a negative number if the first value should be sorted lower

  var arr1 = [-10, -5, -1, 0, 2, 6, 8];
  var arr2 = ["a","b", "c", "A", "B", "C"];
  arr1.sort(function(a,b){return a-b;});
  document.write(arr1 + "<br>");
  arr1.sort(function(a,b){return Math.abs(a)-Math.abs(b);});
  document.write(arr1 + "<br>");
  document.write(arr1 + "<br>");
  document.write(arr2 + "<br>");
  arr2.sort(function(a,b){return a.toUpperCase()>b.toUpperCase();});
  document.write(arr2 + "<br>");



Output from ch0205.html

Applying Logic

Like any other programming language, JavaScript provides the basic logic operators and operations. The following sections provide phrases on using the JavaScript comparison operators to generate if/else blocks, loops, and a variety of other logic.

Determining If an Object Is Equal To or Less Than Another

var x=5;
var y="5";
var resultA = x==y; //Evaluates to true
var result = x===y; //Evaluates to false

JavaScript uses the standard ==, !=, >, <, >=, <= operators to compare two objects. It also includes the === and !== operators that are type sensitive. For example, 1=="1" evaluates to true, whereas 1==="1" does not because the first is a numerical type and the second is a string type.

Adding Conditional Blocks of Code

if (age >= 100){
  document.write("Wow you are a centurian!");
} else if (age >= 18) {
  document.write("You are an adult.");
} else {
  document.write("You are a child.");

If blocks are created using the basic if (comparison) {IF_BLOCK}. The if block can be followed up by an additional else block using else{ELSE_BLOCK}. In addition, you can add a condition to the else block using else(condition){ELSE_BLOCK}.

Using a While Loop

var weekdays = ["Mon", "Tue", "Wed", "Thur", "Fri"];
  var day = weekdays.pop();
  document.write(day+", ");
} while (day != "Wed");
//Output is "Fri, Thur, Wed, "

The while(condition){LOOP_BLOCK} and do{LOOP_BLOCK}while(condition); loops allow you to loop through code until a specific condition occurs. The code in your LOOP_BLOCK is executed each time through the loop.

Iterating Through Arrays

var weekdays = ["Mon", "Tue", "Wed", "Thur", "Fri"];
for(var x=0; x < weekdays.length; x++){
//Output is "Mon|Tue|Wed|Thur|Fri|"

The best method to iterate through JavaScript arrays is to use a for(init; condition; adjustment){LOOP_BLOCK} loop. The for() loop allows you to initialize a variable and then iterate through until a condition is met. To loop through the array, initialize an index and then stop the loop when the index is equal to the length of the array.

Iterating Through Object Properties

var obj = {first:"Bilbo", last:"Baggins", title:"Hobbit"};
for (var key in obj){
  document.write(key + "=" + obj[key] + "&");

JavaScript provides an additional type of option in the for() loop. Using the in keyword, you can iterate through the values in an array or the properties in an object. The syntax is for( var name in object){LOOP_BLOCK}. The name is assigned the property name inside theLOOP_BLOCK.

Math Operations

JavaScript has a built-in Math object that provides functionality for extended mathematical operations. The Math object has property values, listed in Table 2.2, that contain the most common constants. You can access the Math object directly from your JavaScript code. For example, to get the value of pi, you would use the following:



Table 2.2 Math Object Properties

The Math object also includes several methods that allow you to apply higher math operations. The following sections provide phrases for those operations.

Generating Random Numbers

// Random number between 0 and 1
//Random number between 1 and 10
Math.floor(Math.random() * 10) + 1;
//Random number between -10 and 10
Math.floor(Math.random() * 20) - 10;

The Math.random() function generates a random float value between 0 and 1. To convert that to an integer, multiply the results of Math.random() by the maximum value you want for the integer and then use Math.floor() to round it down.

Rounding Numbers

var x = 3.4;
var y = 3.5;
Math.round(x); //returns 3
Math.round(y); //returns 4
Math.ceil(x); //returns 4
Math.ceil(y); //returns 4
Math.floor(x); //returns 3
Math.floor(y); //returns 3

The JavaScript Math object provides three methods to round numbers. The .round() method rounds numbers #.5 up to the next higher integer and numbers #.49999... down to the next lowest integer. The .ceil() always rounds up to the next highest integer. The .floor()always rounds down to the next lowest integer.

Getting the Minimum Number in a Set

Math.min(8,"0x5",12,"44",8,23,77); //returns 5
var arr1 = [4,8,12,3,7,11];
Math.min.apply( Math, arr1 ); //returns 3
var arr2 = ["0x5",8,12,"4",8,23,77,"0x1F"];
Math.min.apply( Math, arr2 ); //returns 4

The Math.min(item, item, ...) method allows you to find the smallest number in a set. You can also apply an array object to the .min() method using Math.min.apply(Math, array). This returns the smallest number in the array. The array can contain string representations of numbers, such as "4" and "0x5B", but not character strings such as "A". If the array contains character strings, the result will be NaN.

Getting the Maximum Number in a Set

Math.max(8,"0x5",12,"44",8,23,77); //returns 77
var arr1 = [4,8,12,3,7,11];
Math.max.apply( Math, arr1 ); //returns 12
var arr2 = ["0x5",8,12,"4",308,23,77,"0xFF"];
Math.max.apply( Math, arr2 ); //returns 308

The Math.max(item, item, ...) method allows you to find the largest number in a set. You can also apply an array object to the .max() method using Math.max.apply(Math, array). This returns the largest number in the array. The array can contain string representations of numbers such as "26" and "0x1F", but not character strings such as "A". If the array contains character strings, the result will be NaN.

Calculating Absolute Value

Math.abs(-5); //returns 5
Math.abs(5); //returns 5
Math.abs("-15"); //returns 15
Math.abs("0xFF"); //returns 255

The Math.abs(x) method returns the absolute value of x. The variable x can be a number or a numerical string such as "5", "-5", or "0xFF".

Applying Trigonometric Functions

Math.log(2); //returns 0.693
Math.sin(0); //returns 0
Math.cos(0); //returns 1
Math.tan(1); //returns 1.5574

The Math object provides several trigonometric methods that apply trig functions to numbers. Table 2.3 lists the trig methods to apply things such as natural logs, sine, cosine, and tangent operations.


Table 2.3 Match Object Trigonometric Methods

Applying Power Functions

Math.exp(4); //returns 54.59815
Math.pow(2,16); //returns 65536
Math.sqrt(25); //returns 5

The Math object provides several power functions that allow you to apply exponential and root operations on numbers. Table 2.4 lists the trig methods to apply Euler’s exponential, power, and square root functions. You can pass in the values as numbers or numerical strings.


Table 2.4 Match Object Trigonometric Methods

Working with Dates

A useful built-in JavaScript object is the Date object. The Date object allows you to get the user’s time by accessing the system clock through the browser. This allows you to use JavaScript to get the local time for the user. The Date object also provides methods for manipulating the time values to determine time deltas and generate time and date strings.

Creating a Date Object

var d = new Date();
//Wed Jan 30 2013 09:37:42 GMT-0700
var d = new Date(1209516513246);
//Tue Apr 29 2008 18:48:33 GMT-0600
var d = new Date("May 17 2014 13:55:13 GMT-0600");
//Sat May 17 2014 13:55:13 GMT-0600
var d = new Date("1/1/2020");
//Sat Jan 01 2020 00:00:00 GMT-0700
var d = new Date("12/12/2012 12:12:12");
//Wed Dec 12 2012 12:12:12 GMT-0700
var d = new Date(2014, 8, 6, 16, 5, 10, 3);
//Sat Sep 06 2014 16:05:10 GMT-0600

A Date object represents a specific date and time with millisecond granularity. To create a Date object, all you need to do is call a new Date() using one of the following methods. The dateString can be in one of several different formats, such as "7-17-2013", "11/22/2014 10:12:05", "Dec 12 2012 12:12:12", and "2014-01-05T08:03:22.356Z".

Image new Date();

Image new Date(milliseconds);

Image new Date(dateString);

Image new Date(year, month, day, hours, minutes, seconds, milliseconds);

Getting the Current Date and Time

new Date();

To get the current date and time, create a new Date() object without passing parameters. This creates an object with the current date and time.

Creating a Date String

var d = new Date();
//Returns Sat May 17 2014
//Returns Saturday, May 17, 2014
//Returns 2014-05-17T19:55:13.000Z
//Returns Sat, 17 May 2014 19:55:13 GMT
//Returns Sat May 17 2014 13:55:13 GMT-0600 (Mountain Daylight Time)

There are several methods to generate a date string from JavaScript. The first step is to get a Date object. The Date object provides the following methods that return differently formatted date strings:

Image .toDateString()—Returns an abbreviated date string.

Image .toLocaleDateString()—Returns a localized date string.

Image .toISOString()—Returns the ISO standardized date string.

Image .toUTCString()—Returns a date string converted to UTC time.

Image .toString()—Returns the full date string with time zone and more.

Creating a Time String

var d = new Date();
1:55:13 PM
13:55:13 GMT-0600 (Mountain Daylight Time)

The Date object also allows you to get just a time string. There are two methods attached to the Date object that return a time string. The .toTimeString() method returns a time string with the time, time zone, and even daylight savings time information. The.toLocaleTimeString() returns a more basic time string with local formatted time.

Getting a Time Delta

var atime = new Date("2014-01-05T08:03:22.356Z");
var btime = new Date("2014-01-05T09:08:57.758Z");
var delta = Math.abs(btime - atime); //3935402ms
var totalSec = Math.floor(delta * .001); //3935s
var hours = Math.floor(totalSec / 3600); //1hr
var minutes = Math.floor(totalSec / 60) % 60; //5min
var seconds = totalSec % 3600 % 60; //35sec

Date objects essentially represent the number of milliseconds from Jan 1, 1970. Therefore, you can get the time difference between two Date objects by subtracting them from each other. The result is a number that represents the millisecond difference between the two dates.

By the way

When subtracting two dates to get the millisecond delta between them, you can end up with a negative number depending on which date is subtracted from the other. Use Math.abs(timeA-timeB) to always generate a positive time delta.

Getting Specific Date Components

var d = new Date("Sat Jan 04 2014 15:03:22 GMT-0700");
d.getDate(); //returns 4
d.getDay(); //returns 6
d.getFullYear(); //returns 2014
d.getHours(); //returns 15
d.getMinutes(); //returns 3
d.getMinutes(); //returns 22
d.getTime(); //returns 1388873002000
d.getTimeZoneOffset(); //returns 420

The Date object provides several methods to get the value of specific components of the date, such as year, day of month, day of week, and more. Table 2.5 lists the methods to get specific date components from the Date object.


Table 2.5 Date Object Methods to Get Specific Date Components

Did you know?

Date objects also have methods to obtain the UTC components by placing UTC after get, such as getUTCHour() and getUTCSeconds().

  var atime = new Date("2014-01-04T08:45:22.356Z");
  var btime = new Date("2014-01-04T12:12:57.758Z");
  var delta = Math.abs(btime - atime); //3935402ms
  var totalSec = Math.floor(delta * .001); //3935s
  var hours = Math.floor(totalSec / 3600); //1hr
  var minutes = Math.floor(totalSec / 60) % 60; //5min
  var seconds = totalSec % 3600 % 60; //35sec
  document.write("Total Milliseconds: " + delta + "<br>");
  document.write("Total Seconds: " + totalSec + "<br>");
  document.write("Delta: " + hours + "hrs ");
  document.write(minutes + "secs " + seconds + "s");


Total Milliseconds: 12455402
Total Seconds: 12455
Delta: 3hrs 27secs 35s

Output from ch0206.html