What Is JavaScript?

  • 9/15/2012

Writing Your First JavaScript Program

In this section, you create your first JavaScript program. As a side effect of doing so, you also create your first webpage with HTML.

JavaScript is tool-agnostic, meaning you can use any text editor or Integrated Development Environment (IDE) to write JavaScript. For example, Microsoft Visual Studio provides a powerful development experience for writing JavaScript. The same can be said for Eclipse, the open-source IDE. However, an IDE is certainly not a requirement for creating and maintaining JavaScript. You can also use a simple text editor such as Notepad or a more powerful text editor such as Vim to write JavaScript.

You’re only a few pages into this book and you already have an important decision to make: What tool should you use to write JavaScript? The guidance I can offer for this choice is limited because I believe you should use whatever tool you’re comfortable with for programming. If JavaScript required a specialized IDE, the choice would be easy: you’d have to use that IDE. However, you can write JavaScript in anything from a simple text editor to a full programming IDE such as Eclipse or Visual Studio, so some might even argue that it’s easier to just use a text editor.

For much of the independent web development and JavaScript writing that I do, I use Vim, because it’s lightweight and gets out of the way. However, I also use Eclipse and Visual Studio for development, depending largely on the platform for which I’m writing code. The choice is yours as to how you prefer to develop JavaScript. Although this book shows examples in Visual Studio, you shouldn’t feel that you must use that IDE to work with the code in this book. The one area where Visual Studio makes your life easier is when writing Windows 8 Apps. I’ll stop short of saying that Visual Studio is required when writing JavaScript-based applications for Windows 8, but for the purposes of this book, Visual Studio is the platform you should expect to see for the Windows 8 chapter.

If you choose to not use Visual Studio, I’ll assume you have a way (and the knowledge) to view the HTML pages you produce in a web browser. Many of the early examples won’t require a web server, but the later chapters do require a web server. (Visual Studio includes a suitable web server.)

This book uses the Express Edition of Visual Studio 11 throughout. Visual Studio 11 Express Edition is available at no cost from Microsoft as explained in the following sidebar. No prior knowledge of Visual Studio is required for this book. Additionally, and just as importantly, writing JavaScript for the browser doesn’t require the advanced features of Visual Studio. What you need to know will be shown along the way to complete a task, but you do need to have Visual Studio installed first.

Writing JavaScript in Visual Studio 11

Writing JavaScript in Visual Studio 11 involves setting up a new project and writing the script or scripts to be used on the page or pages involved in your web application. If you’re using a text editor or a different IDE, you can follow these examples and simply view the resulting file within a web browser locally. For this example, you create a simple webpage that displays text using JavaScript, in the same way that the first example showed earlier in the chapter.

The first step in programming JavaScript with Visual Studio is to create a new project. As a developer, you have a choice of several templates for beginning a project. For this example and most examples in this book, you’ll use the ASP.NET Empty Web Application template, which is found in the Web category. The ASP.NET Empty Web Application template avoids much of the proprietary ASP.NET-related material that’s not necessary for creating a JavaScript web application. Here are the steps:

  1. Within Visual Studio, choose File, New Web Site.

  2. In the New Web Site dialog that appears (shown in Figure 1-4), select the ASP.NET Empty Web Site. In the Web location text box, type StartHere as the name, (you might need to scroll to the right to get to the end of the File System and then click OK to create the website).

    Figure 1-4

    Figure 1-4 Creating an ASP.NET Empty Web Application project in Visual Studio 11.

    A blank, empty project opens, like the one shown in Figure 1-5.

    Now it’s time to add a file to the project.

    Figure 1-5

    Figure 1-5 An empty web project in Visual Studio 11.

  3. For this first example, add an HTML file. On the File menu, select New File.

    The New File dialog box appears, such as the one shown in Figure 1-6.

    Figure 1-6

    Figure 1-6 The New File dialog within Visual Studio 11 is where you add new files to your project.

  4. Click HTML Page, change the name to index.html, and then click Add.

    Depending on the version of Visual Studio you’re using, you might see a basic HTML page that uses an XHTML document type similar to that in Figure 1-7. Some versions of Visual Studio use an HTML5 doctype as you’ve seen throughout the chapter, so your screen might look different than this.

    Figure 1-7

    Figure 1-7 A beginning page with Visual Studio 11.

  5. If your version of Visual Studio has the XHTML doctype as shown, the first thing you need to do is switch the DOCTYPE for the page. If your doctype is already the HTML5 doctype (<!DOCTYPE html>), there’s nothing to change and you can skip this step. If you need to change it, highlight the entire DOCTYPE declaration in Visual Studio and delete it. Replace that long (and ugly) DTD with the following:

    <!DOCTYPE html>
  6. Within the <html> declaration, remove the xmlns namespace attribute. This applies only if it’s present. Some versions of Visual Studio don’t have this attribute present. If it’s not there in yours, you don’t need to change it.

    Regardless of the version of Visual Studio you have, you need to change the <title> tag so that it contains the words Start Here. With those three changes (which you can find in the companion content as index.html), the page should look like this:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Start Here</title>
    </head>
    <body>
    </body>
    </html>

    The file is still unsaved and will have the default name chosen by Visual Studio, as seen in Figure 1-8. It’s time to save the file and view it in a web browser.

    Figure 1-8

    Figure 1-8 Making basic edits on your first webpage through Visual Studio.

  7. If you haven’t already saved the file, save it now. On the File menu, click Save or use the Ctrl+S keyboard shortcut. In some versions of Visual Studio, you’ll see a Save File As dialog, as shown in Figure 1-9. Save the file within your project, and name it index.html. Note that you might not see this dialog at all if you’re using Visual Studio Express Edition for Web.

    Figure 1-9

    Figure 1-9 . Saving the webpage as index.html within the project.

  8. With the file saved, the next step is to view it in a browser. The easiest way to do this in Visual Studio is to click the Run button on the toolbar or select Start Debugging from the Debug menu. When you do so, Visual Studio performs some background tasks, starts a web server (Internet Information Services, or IIS), and launches your default web browser. Note that you might see a dialog indicating that debugging isn’t enabled. Accept the default, and click OK to modify the web.config to enable debugging.

    If all goes well, you eventually see a page like that shown in Figure 1-10.

    Figure 1-10

    Figure 1-10 A successful run of your first webpage.

    If you see a screen like that in Figure 1-10, your project ran successfully. Even though the page itself is blank, notice that the title bar reads “Start Here,” thanks to the change you made to the <title> tag in the page.

  9. Close your web browser.

    Closing your browser has the effect of stopping the project from running, and you’ll be back at the source window for your index.html page.

  10. Within index.html, add the following code between the opening <body> tag and the closing </body> tag (saved as index-wjs.html in the companion content):

    <script type="text/javascript">
        document.write("<h1>Start Here!</h1>");
    </script>

    The code for the final page will look like this:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Start Here</title>
    </head>
    <body>
        <script type="text/javascript">
            document.write("<h1>Start Here!</h1>");
        </script>
    </body>
    </html>
  11. To run that code, on the Debug menu, click Start Debugging, or on the toolbar, click the green Run button.

    You’ll now see a webpage like the one in Figure 1-11.

    Figure 1-11

    Figure 1-11 Running your first JavaScript program.

    Congratulations! You successfully created your first JavaScript program with Visual Studio. Prior to closing Visual Studio, you’ll add two folders in preparation for future chapters.

  12. In the Solution Explorer (normally on the right), right-click the name of the site, StartHere, click Add, and then click New Folder. Name the folder js.

  13. Add another folder by using the same process: in Solution Explorer, right-click the StartHere project, click Add, and then click New Folder. Call this folder css. Your final Solution Explorer should look like Figure 1-12.

Figure 1-12

Figure 1-12 The final Solution Explorer with two folders added.

JavaScript’s Limitations

Prior to wrapping up the chapter you should see some of the limitations of JavaScript. Some of these are subtle and might not be obvious. JavaScript’s largely client-side role means that there are some inherent issues you need to consider when developing with the language.

Don’t Rely on JavaScript for Data Security

JavaScript executes on the client. This means that anything—including data, or even the program itself—can be manipulated by users in any way they deem necessary. Users will try to send bad data back (for example, changing item prices in a shopping cart or anything they can get their virtual hands on), and they’ll also try to inject scripts or their own programs into your code so that it gets executed by your server.

You should always assume that data is incorrect when it arrives back at your server, whether it’s from a web form or through JavaScript. Only after proving, within your server-side programs, that the data is valid should you proceed to use it within an application. Under no circumstances should you use data without validating it on the server side, when it is under your control.

This warning specifically includes any JavaScript-based validation of form data. For example, JavaScript is frequently used to provide instant feedback to a user typing into a web form. However, just because there is JavaScript validation in place to ensure that data is properly formatted in the browser doesn’t mean that it’s actually formatted correctly. This data needs to be checked again on the server.

This is an area where I’ve seen developers attempt all sorts of trickery to make sure that the JavaScript’s validation occurs rather than just check the data within the server program. None of the tricks work, so the time is better spent validating in your server-side program rather than attempting to add another layer of complexity.

One common misconception is that using a POST request rather than a GET request will keep the data secure. This is not true. Data sent by using POST is just as vulnerable as that sent through a GET (where the parameters show up in the address bar). So what can you do? Check the data in the server program.

You Can’t Force JavaScript on Clients

A visitor’s web browser might not run JavaScript, or it might not run the version of JavaScript your program needs. As a developer, you must consider the case where JavaScript isn’t available on the client, whether by their choice, due to accessibility, because of a device limitation, or for any reason. Your pages should work without JavaScript by providing an alternative means for accomplishing the task or interacting with your application and content.

However, today’s advanced applications sometimes do require JavaScript. In such cases, you should detect which features are and aren’t available and provide messaging to the user indicating that JavaScript is required for the application.

In essence, the only way you can fail is by assuming JavaScript will always be available and, hence, neglecting to create a way to handle its absence.

A variation of this problem is that the versions of JavaScript and their implementations vary widely between web browsers and between versions of the browsers. JavaScript is defined in the ECMA-262 specification, but each browser vendor interprets that specification slightly differently, in much the same way that those same browser vendors interpret HTML and CSS standards differently. The good news is that there’s always work for people who understand these browser differences; the bad news is that it can be very frustrating and time consuming to allow for such differences in your code so that it works in whatever browser your visitors are using.

This problem is slowly becoming less and less important. Inside organizations that standardize on specific browsers and versions, it’s a minor problem. However, if your application will be used on the Internet, you need to accommodate differences between web browsers. The primary way to find out if your page works in other browsers is to test it in other browsers. This is not terribly difficult to do, but recently it has become even more cumbersome with the advent of mobile devices, which have their own browser implementations.

Microsoft provides free Application Compatibility images for Virtual PC. These are full operating systems with various versions of Internet Explorer installed on them. The current link for these is http://www.microsoft.com/download/details.aspx?id=11575, but if that link changes, an Internet search for “Internet Explorer Application Compatibility VPC” should result in the updated location for those images.

Other browsers such as Chrome, Firefox, and Safari are free downloads. I recommend that you acquire them and test your applications in those browsers, as well.