9781430237891_CO-01.jpg

Chapter 8

JavaScript Primer

In this chapter, we will start to talk about JavaScript and programming in general. Along the way, we will explore the building blocks of programming logic as they exist in JavaScript. But before we do this, let’s look back at the history of JavaScript, so as to get the full context of what has gone before and to see the bigger picture of the major events that have shaped the modern landscape of JavaScript.

Since the goal of this chapter is to give an introduction to JavaScript, you can skip this chapter if you already have a passing knowledge of JavaScript. You can also skip it if you know what variables are or how to construct a conditional statement or loop. On the other hand, you should definitely read this chapter if you’ve ever edited someone else’s code, but weren’t sure about what it did, line for line. This chapter will help you ensure you are well versed in the basics of the language.

What is JavaScript?

JavaScript is the scripting language of the Web. It is embedded in our HTML pages, executed by an interpreter that is built into the browser, and has access to all of the HTML elements on the page. As such, we can use it to add interactivity to our pages. We can also use it to load and parse information from external sources or even from our end users. Modern JavaScript is sleek, nuanced, and an integral part of any web developer’s skill set.

A brief history of JavaScript

Before we dig into the specifics of JavaScript, let’s look back a little on the history of the language and how its usage has evolved over time (see Figure 8-1).

9781430237891_Fig08-01.jpg

Figure 8-1. Notable events in the history of JavaScript

Early history

Brendan Eich created JavaScript while working at Netscape. The language was intended to serve as the glue language of the company’s browser, so he added scripting capabilities to the front-end. By his own account1 he was recruited to work at Netscape with the intent of implementing a Scheme interpreter in the browser. The language was initially codenamed Mocha, then called LiveScript when it was first released in Netscape version 2.0 beta. Finally, it was renamed to JavaScript in 1995 with the release of Netscape Navigator version 2.0B3.

Keep in mind that it was a different world in 1995. The two main browsers on the market were Netscape Navigator and Internet Explorer. Internet Explorer was not yet integrated into the operating system, and neither browser was free, let alone open source.

JavaScript was clearly well received because within a year it was reverse-engineered, rebranded as JScript, and included in Internet Explorer along with what Microsoft hoped would be a direct competitor to the JavaScript language: VBScript.

As a side note: While VBScript went on to have success in other domains—as the language of choice for ASP and as the glue language within Microsoft Office products—it was never embraced by the web development community as a client-side scripting language. This was mainly because only IE supported it, while JavaScript was supported in every browser (even if it was sometimes, unfortunately, called JScript).

It was in this climate—and perhaps partly as a result of the attempt to dilute the brand—that Netscape submitted JavaScript to the ECMA Committee (later to be known as Ecma International) to be standardized as ECMAScript.

For context, Ecma International is a non-profit international standards organization. ECMA is an acronym that stands for European Computer Manufacturers Association. Ecma International is also responsible for many other standards, including the C# language specification, the FAT file system, and the Eiffel language.

Modern JavaScript

In this way, JavaScript continued to grow in adoption and popularity in tandem with the expansion and growth of the Web and the refinements of the browsing experience. ECMA continued to release new updates to the standard, and the browsers themselves added their own improvements via localized dialects.

Easily the most notable localized improvement was the XMLHttpRequest object (XHR) , which led to the innovation of Ajax (Asynchronous JavaScript and XML) . Interestingly, XHR started life as an ActiveX Control in IE 5 before being adopted as a JavaScript object in localized browser dialects.

With the introduction of XHR, web developers could finally, from the client-side, send data to or receive data from a web server either synchronously or asynchronously. This innovation expanded the scope of what could be done with web applications, but it also increased the complexity of web development in general.

To keep up with the higher level of demands that this new complexity put on their products, the browser makers—of which there were many more of by now—were putting considerable effort into refining and streamlining their own proprietary JavaScript interpreters (or JavaScript engines, as they are sometimes called). As of this writing, there are five mainstream JavaScript engines:

  • Nitro for Safari
  • V8 for Chrome
  • SpiderMonkey for Firefox
  • Carakan for Opera
  • Chakra for IE

With all of this increased complexity, both in the capabilities of the technology as well as the potential for efficiency in the browsers, web developers also had to level up their own skills. Think about it: it was now possible to load new content into a page at run time, but this introduced new issues. What happens to the current state of all the information currently stored on the page when it is updated or replaced with the new content? If the new content is loaded asynchronously, what is the state of the page while you’re waiting for the data? What happens if the data never loads? And will the new data stomp all over the existing data?

With the greater demand for code craftsmanship in web development, the best parts of the language were being mainstreamed, and the flaws were getting workarounds.

And while web developers were getting more and more adept at using the intricacies of JavaScript, they were also developing frameworks and libraries to speed up development and take care of the lower level functionality. Prototype, JQuery, and a host of other JavaScript frameworks emerged. Each allowed web developers to achieve more and do it faster, but at the cost of learning a new way to do things.

That brings us to the current day. There continues to be new innovation with JavaScript, most recently with frameworks such as Jasmine and QUnit to facilitate unit testing for test driven development (TDD), which we will get to in Chapter 10. You can also see this innovation in new frameworks such as Node.js, which enables server-side development in JavaScript.

JavaScript the basics

OK, now that we have the full context for how JavaScript came to be, let’s start exploring the fundamentals of the language.

Code placement

JavaScript can be included in a document either by placing script tags inline in the document or by linking to an external JavaScript document. Whichever way you choose to include your JavaScript, it can only be included either in the head or body section of the page.

Inline JavaScript looks something like this:

 <script>
 //some javascript here ...
 </script>

When including JavaScript externally, you put the URL to the external file in the src attribute of the script tag and set the type to "text/javascript" so that the browser knows how to interpret the new data being loaded in:

 <script src="[url to external js file]" type="text/javascript"></script>

The external file should be named with a .js extension and have just pure JavaScript in it, without any script tags or any HTML tags at all.

How you include your JavaScript is up to you. You may choose to include JavaScript externally to share core functionality across your entire web application. But doing that means that the browser must make an HTTP call for each file included. This can increase the amount of time needed to load the JavaScript. You may choose to include all of your JavaScript inline on your page to reduce the amount of HTTP calls, but doing this will increase the overall size of the page that your browser has to download and interpret. There is no single right answer; it’s up to you to determine what is best for the functionality of your web application, how large your pages are, and what your target audience is using to access your site.

Tip: It is sometimes useful to have all of your JavaScript loaded at the bottom of the page. This is because the browser interprets the page top down. Putting the external scripts at the bottom allows the page be rendered to the end user first, before it begins interpreting the JavaScript. This creates the perception of a faster loading page. If you do this, however, make sure that nothing on the page is dependent on objects in JavaScript being present on page load.

Code execution

Code placed at the root level of the script tag or at the root level of the JavaScript document will execute as soon as it is loaded. The only way to delay this execution is to wrap the code in a function, since a function will not run until it is invoked:

 <script>

 // this will run as soon as it is read by the browser

 var userMessage="hello, world!";

 //this will run only when it is invoked

 function initialize(){

  var msg = "hi there";

 }

 </script>

Commenting your code

The preceding example includes lines beginning with two forward slashes. These lines are commented out. Comments are lines in your code that are not executed by the interpreter. Usually you put comments in your code to leave notes about the code, for yourself and for whoever is going to read the code after you.

There are two kinds of comments in JavaScript: single line comments and multiline comments.

Single line comments begin with two forward slashes. Anywhere you insert these two forward slashes begins a comment, and the interpreter will ignore everything that follows them until it hits a new line. The following snippet shows valid examples of single line comments:

 <script>

 // this is a comment

 var tempData = "" // this is a comment, probably about tempData

 function initialize(){ // this is a comment, probably about the initialize function

 }

 </script>

Multiline comments begin with a forward slash and an asterisk (/*), and they end with an asterisk and another forward slash (*/). Anything between the opening and closing of the comment is ignored by the interpreter. What follows is an example of a multiline comment:

 <script>

 /*

  this is a multiline comment

  used to denote blocks of

  comments across multiple lines

 */

 </script>

Why would you want to comment your code? Commenting your code makes it more readable, in that you and others can easily tell what is happening on the page. This will benefit you when you return to the code after days, months, or even years of working on other things. It will also help the next developer that takes on your code. This second part is very important; the world is becoming increasingly smaller, and the reputation that you build in your peer community around the code that you leave for the next person to pick up can have an impact on you in the future. There are many ways to make your code readable, and commenting is just one of them. We will point out additional ways to make your code more readable as you progress through the book.

Expressions, white space, semicolons, and minification

Every language, including spoken and written languages, has syntax. Merriam Webster 2 defines syntax as follows:

the way in which linguistic elements (as words) are put together to form constituents (as phrases or clauses).

To apply this to JavaScript, sentences are called expressions. Expressions are composed of keywords, variables, and values.

Keywords , or reserved words, are words that have special meaning in the language because they are used to define the native functionality. Variables, which we will explore in much more detail very soon, are words that we create to hold data, or values.

Expressions end in semicolons, and words in expressions are separated by white space. The following snippet shows several examples of expressions:

 <script>

 var expressionExample = "";

 sum = 421 + 42;

 var anonFunction = function(){

  //some functionality

 };

 </script>

Expressions also evaluate to values.

Tip: The JavaScript interpreter ignores unneeded white space (spaces, tabs, and new line characters), so you can reduce the size of your JavaScript files by minifying them. Minification removes the unneeded white space, as well as comments, from your code. A couple of popular minification tools are JSMin ( http://crockford.com/javascript/jsmin ) and YUI Compressor ( http://developer.yahoo.com/yui/compressor ).

Variables

Variables are blocks of memory that you can assign a name to. You use them to store, update, and retrieve data. Think of it like this: your computer—or phone or device or whatever—has a finite amount of resident memory. Resident memory is RAM, and it loads up and is available for storage at run time. The browser you have running has a footprint in resident memory, and this is the amount of memory the browser takes up and has allocated for its usage. When you create variables in your code, the browser—via the JavaScript interpreter—allocates a chunk of memory from this footprint and gives it the name that you assigned to it, allowing you to use that chunk of memory (see Figure 8-2).

9781430237891_Fig08-02.jpg

Figure 8-2. Resident memory

You create variables in JavaScript using the var keyword:

 <script>

 var newVariable = "";

 </script>

When creating multiple variables, you can queue their initialization up in one expression, separated by commas. This saves you the trouble of typing var over and over again, and it reduces the amount of characters in your JavaScript files. Consider the following example:

 <script>

 // this is grossly inefficient, 30 characters in total not counting new lines

 var a = 1;

 var b = 2;

 var c = 3;

 // this is more streamlined, minified it only takes 16 characters, 53% the size of the ➥

  above example

 var a=1,b=2,c=3;

 /* this makes it more readable, and if you automate minification before releasing to ➥

  production you still get the improvement from the above example*/

 var a = 1,

  b = 2,

  c = 3;

 </script>

You use variables to store data that you can evaluate and execute on, but what kind of data can you store in variables? JavaScript supports several data types, including String, Number, Boolean, Undefined, and Array. It also supports function and object datatypes. Let’s take a look closer look at each of these datatypes.

The String data type is any alphanumeric character surrounded by single or double quotes:

 <script>

 var myString = "this is a string";

 </script>

The Number data type is any numeric value, including negative numbers, zero, and floating point ­numbers:

 <script>

 var myNumber = 34;

 </script>

The Boolean data type is named after a 19th century mathematician and philosopher who was also one of the founding fathers of computer science: George Boole. It represents the value of either true or false.

 <script>

 var myBool = true;

 </script>

The Undefined data type is used to represent a variable that has been named, but has had no data assigned to it. It is the lack of data type.

The Array data type indicates that the variable contains an array. Arrays are vector data types in that they contain multiple values. Since JavaScript is a loosely typed language, you can store data of any type in an array, even other arrays. When arrays contain other arrays, they are considered multidimensional arrays.

You instantiate a new array either by using the Array constructor or by simply assigning data to a variable in array format; that is, to a variable wrapped in square brackets with a comma separating each value:

 <script>

 var first_list = new Array(); // using array constructor

 var second_list = [583, 103, 902]; // assigning value implicitly creates a new array

 var multidim_list = [ [34, 21, 10] , [88, 310, 34] ]; // a multidimensional array, an array ➥ of arrays

 </script>

You retrieve and set values from arrays via their index number, which is the number in sequential order that they are stored in. Note that all arrays are zero-based, in that the number ordering for arrays starts at zero.

 <script>

 var ind = second_list[0]; // retrieves 583 from the array and stores it in ind

 second_list[2] = 20; // overwrites the previous value with 20

 </script>

The other data types that JavaScript supports are functions and objects, both of which we will talk about at length next.

Data types define the kinds of data that you can store in variables, but JavaScript is a loosely typed language (another term for this is weakly typed language ). This means that, when you declare a variable and assign data of one type to it, you can then go and assign data of a completely different type to that same variable. The example that follows is perfectly valid JavaScript:

 <script>

 var userName = "[email protected]";

 userName = 21; // userName was a string, now it's a number

 //the below code shows that arrays can hold data of different types

 var myCollection = [23, "test data", true, true, false, -120, [20, "[email protected]"]];

 </script>

This approach is in contrast to languages that are strictly typed (another term for this is strongly typed). With strictly typed languages, you must declare the data type of a variable when you create it, and that variable can only hold that type of data.

This has implications for how you can safely code. With loosely typed languages, you don’t need to cast (i.e., convert) your variables to different types, and your arrays are much more flexible. But with loosely typed languages, you can never assume you know what the data type of your variable is.

JavaScript has the typeof operator, which allows you to inspect a variable to see what data type it contains:

 <script>

 var myVar = "";

 alert(typeof myVar);

 </script>

Now that we know what variables and expressions are, let’s look at how we can take action on variables to create more complex expressions.

Conditionals and operators

You can control the flow of logic in your applications by testing the value in your variables or testing what expressions evaluate to. You perform these tests in conditional statements. JavaScript supports the following conditional statements: if, else, and else if.

Using conditional statements

You structure if -else statements like this:

 if([some condition to test]){

  //execute this block if condition evaluates to true

 }else{

  //execute this block if condition evaluates to false

 }

You may also follow an if with an else if; such a statement would be structured like this:

 if([some condition]){

 }else if([some different condition]){

  //execute this block if the second condition is true

 }

The preceding examples use the if keyword to test a condition; that condition is wrapped in parentheses. Conditions usually evaluate a variable, and they might test an upper limit of a list, check whether a variable contains the expected type of data, or examine something similar. Curly braces surround blocks of code, which are just groups of expressions, as shown in the following example:

 <script>

 var userName = "[email protected]",

  passWord = "test123";

 if(passWord.length > 0){ //if the variable has data in it

  submitCredentials();

 }else{ //if the data does not have data in it

  promptForCredentials();

 }

 </script>

The preceding example is ludicrously simplistic, but with it we can start to see how the concepts we’ve learned so far work together. We create two variables, and then we test that one of the variables—the password—has data in it. If it does, then we submit the variable for further execution. If it doesn’t, then we prompt the user to enter new credentials.

This technique controls the flow of logic with a conditional statement.

Using operators

You use operators to test conditions. JavaScript supports the following operators: comparison, arithmetic, assignment, logical, and ternary. The upcoming sections examine these operators in greater depth:

Comparison operators

== This is the equality operator; it tests whether values on either side of it are equal. This operator tests the values, but not the data types:

if ( sum == 10){
}
=== This is the strict equality operator; it tests whether both the values and the data types on either side of the operator are equal:

if (sum === "10"){
// this is only true if sum is a string
// that is equal to "10"
}
!= This is the inequality operator.
!== This is the strict inequality operator.
<=, <, >, >= These operators are less than, less than or equal to, greater than, and greater than or equal to, respectively.

Arithmetic operators

+ When used on numbers, this is the addition operator:

var sum = 45 + 19;

When used on strings, this becomes the concatenation operator, joining together two or more strings into a single string:

var username = "[email protected]";
var msg = "Welcome, " + username; //produces Welcome, [email protected]
Note that when this is used on a combination of strings and numbers, the numbers get converted to strings and string concatenation is performed, instead of numeric addition.
- This is the subtraction operator.
/ This is the division operator.
* This is the multiplication operator.
++ This is the increment operator; it adds one to the value that it is used on:

  var runningTotal = 1;
runningTotal++; //now contains 2
-- This is the decrement operator; it subtracts one from the value that it is used on.
% This is the modulus operator. When used with two numbers, it performs division and returns the remainder of that calculation.

This is most useful when programmatically drawing out a grid or when figuring out alternating rows.

• In the case of drawing a grid, when iterating you simply get the modulus of the current iteration and the number of columns in the row. When the modulus is zero, you start a new row.

• In the case of alternating rows, you do the same as above, but you get the modulus of the current iteration and learn whether the current row is an odd or even row number.

We will talk more about iterations soon.

Assignment operators

= This is the assignment operator; it is used to assign value to variables.
+=, -=, *=, /= These operators are all shorthand to perform arithmetic and assign values at the same time:

sum += 3; // adds 3 to the value of sum
diff -= 1; // subtracts 1 from the value of diff
prod *= 2; // multiplies the value of prod by 2

Logical operators

&& This is the logical AND operator. This groups together two or more conditions, and all must equate to true for the overall aggregate to equate to true:

if((x >0) && (x <=10)){
// x must be both greater than 0 and less
// than or equal to 10 in order for
// this condition to be true
}
|| This is the logical OR operator. Like the logical AND operator, this groups together two or more conditions, but only one of the conditions must be true for the overall aggregate to equate to true.
! This is the logical NOT operator. This tests the inverse of what is in the condition:

if !(x < 10){} // this is true if x is not less than 10

Ternary operator

You can use a ternary operator to replace an if else statement. This is eminently less readable, but will use fewer characters, which technically will equate to a smaller byte size for your JavaScript files. The trade off is up to you and the standards that you adopt in your organization.

The ternary operator is ? : and is structured like this:

 [condition to evaluate] ? [if condition is true] : [if condition is false]

The ternary operator returns a value, so it can be used in variable assignment. Consider the following code example, which creates three variables:

  • A maximum amount
  • A random amount up to that maximum amount
  • A string to demonstrate if the random amount is above or below the midpoint to the maximum amount:

The ternary operator code looks like this:

 <script>

 var ceiling = 100,

  random = Math.random()*ceiling,

  returnValue = (random <= (ceiling / 2)) ? "less than halfway there" : "over halfway there";

 alert(random + " " + returnValue);

 </script>

Iterations

So far we’ve learned to create expressions by declaring variables, assigning values to them, and testing them with operators and conditional statements. But let’s say we want to repeat the same expression or group of expressions multiple times, or step programmatically through each index in an array—this is when we need to use loops, which also called iteration statements.

JavaScript supports several types of loops; the first loop type we’ll talk about is the for loop.

The for loop is composed of three parts:

  • the initializer
  • the condition
  • the incrementor

Each part is separated by a semicolon, and all three are wrapped in parentheses and preceded by the for keyword. The block of expressions that you wish to repeat is wrapped in curly braces. Its structure looks like this:

 for ([initializer] ; [condition] ; [incrementor]) {

  // block of expressions to repeat

 }

Each part of the for loop does exactly what it sounds like it does:

  • The initializer initializes a variable.
  • The condition tests a condition—presumably the variable and the loop will continue to iterate as long as the condition is .
  • The incrementor increments the variable.

The general idea is to increment (or decrement) the variable to eventually make the condition no longer equate to true, so that the loop eventually ends (see Figure 8-3).

9781430237891_Fig08-03.jpg

Figure 8-3. Implementing a for loop

If you play with each part, you can test the boundaries of what the language will support with for loops. For example, you might try declaring and testing multiple variables. You might also try initializing your variable to a high value and then decrementing it to make a countdown, and so on.

Now just mechanically repeating the same thing over and over again is only so useful. It’s the fact that the incrementor changes the value each step through the loop (and we can access its value) that makes the loop so much more interesting.

Let’s say you want to step through each index in an array. To do so, simply use the iterator variable as the index, as in this example:

 <script>

 var my_list = [20, 1003, 394, 2];

 for (var x = 0; x < my_list.length; x++){

  alert(my_list[x]); // using x as the index number

 }

 </script>

JavaScript also supports the while loop, which is structured like this:

 while([condition]){

  //block of code to execute

 }

It also supports the do while, which is structured like this:

 do{

 }while([condition])

A word of caution: The for loop declares an iterator that you test against to end your loop, but the while and do while loops have no such iterator. You must keep track of what you are testing in the condition and make sure this test will eventually evaluate to false; otherwise, your loop will never end (that is, it will become an infinite loop). An infinite loop will cause your application to fail, and most likely cause your browser to crash (more modern browsers have begun to wise up to this issue, and may give the user a chance to kill code that is taking too long to run).

Though they technically do the same thing—repeat a set number of times—the for loop and the while loop are philosophically different. Since the for loop has its termination built in, it is best suited for iterating over a known quantity like an array or properties in an object. The while loop has no built-in terminator, so it will continue to loop while its test condition is true. Therefore, it is best saved for things like a game engine loop where the status is maintained in the loop until user or system events fire to update the status, thus stopping the loop.

Summary

In this chapter, we explored the history of JavaScript and talked about some of the events that shaped and influenced its rise in popularity and complexity. We also dipped our toes into the basics of the language, from creating variables to testing conditions and looping.

These are the building blocks of programming logic. In the next chapter, we will take these concepts and begin to think abstractly in JavaScript with them, using metaphorical concepts like objects and functions—and even delving into the beautiful world of functions as first-class objects.

1 http://brendaneich.com/2008/04/popularity/

2 www.merriam-webster.com/dictionary/syntax

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset