官术网_书友最值得收藏!

JavaScript Syntax and Structure

Now that we've installed an IDE and established how to manage a working project folder within our code editor, it's time to look at how JavaScript code is written and ordered within such an environment. The first thing we need to do is create a set of files within the Project folder because we will write our JavaScript instructions in these. We will create a set of files within the working project folder and then bind them to one another.

Exercise 2.02: Creating Project Boilerplate

The most common environment where JavaScript runs is inside a web browser. For JavaScript to run within this environment, it must be included within a host HTML file in some way. Let's create a basic HTML file and a JavaScript file and instruct the web browser to load our JavaScript file within the HTML at runtime. Let's get started:

  1. Open the working project folder you created previously within your IDE (Visual Studio Code). No files will be listed in the leftmost pane since we haven't created any yet:

    Figure 2.10: The current project contains no files

  2. If you hover your mouse cursor over this leftmost area, you will notice a number of icons appear to the right of the project name. The leftmost of these icons allows for the creation of new files. The one next to it allows the creation of new folders. Click the New File icon:

    Figure 2.11: Clicking the New File icon

    A new file is immediately created and is available for us to name. You should immediately provide a name and file extension. The name should be something that tells you why the file exists, and the extension lets Visual Studio Code and other applications and services understand how to manage and run the file. Type in index.html for the name of the extension of the newly created file. The name index tells us that this file is the root or index HTML file for our project. The .html extension informs both us and the computer as to the nature of this file:

    Figure 2.12: Naming the file index.html

  3. Once complete, hit Enter/Return on your keyboard to commit the change. The file will immediately open in the editing pane of your editor. As you can see, it is completely blank:

    Figure 2.13: The file exists and is open, but it is empty

  4. Type in the following boilerplate HTML code to set up the file's structure:

    <!DOCTYPE html>

    <html lang="en">

      <head>

        <meta charset="utf-8">

        <title>JavaScript Project</title>

      </head>

      <body>

        <h1>Just an HTML page...</h1>

      </body>

    </html>

  5. We declare the file as HTML and establish a <head> tag and a <body> tag. The head of an HTML document includes invisible data such as declaring the character set and title. The body of an HTML document contains visible elements such as text and images. Notice that you must save the file using File | Save or by using Command/Ctrl + S:

    Figure 2.14: Our initial HTML markup structure

  6. Create a new file once again, this time naming it app.js. This will signify that this is the main JavaScript file for the application. The .js file extension indicates an external JavaScript file.
  7. The new JavaScript file will open just like the HTML file did. As you can see, it is also initially empty. Type in the following JavaScript code:

    console.log("app.js JavaScript Included!");

  8. Ensure that you save the JavaScript file again by navigating to File | Save from the application menu or by using the keyboard shortcut Command/Ctrl + S:

    Figure 2.15: You should now have both a JavaScript file and an HTML file

  9. In order to bind the newly created JavaScript file to our HTML so that it can run in the web browser, we must reference it within the HTML file itself. Switch to the HTML file titled index.html from earlier. Place the following code directly following the <title> tag and before the closing tag of the <head> element:

    <script src="app.js"></script>

  10. The <script> tag is used to either include an external .js file, as we are doing here, or it can be used to denote a block of JavaScript code directly within HTML. The full HTML file code should now appear as follows:

    <!DOCTYPE html>

    <html lang="en">

      <head>

        <meta charset="utf-8">

        <title>JavaScript Project</title>

        <script src="app.js"></script>

      </head>

      <body>

        <h1>Just an HTML page...</h1>

      </body>

    </html>

  11. With the new line of code added to the HTML, save the file once again. In Visual Studio Code, a file with unsaved changes is signified with a small, filled disc in the File tab within the project explorer:

    Figure 2.16: A file with unsaved changes

  12. Run the index.html file within a web browser. Open developer tools and activate the Console view. If all goes well, you will see the message we instructed JavaScript to output:

Figure 2.17: The resulting console output

We now know that our project boilerplate has been configured correctly since the HTML is running and has effectively called code from within the JavaScript file. We now have the beginnings of a web application—complete with structure (HTML) and logic (JavaScript) components.

Basic JavaScript Syntax

It is important to know the basic syntax of any programming language in order to write it correctly. To begin writing JavaScript, you'll need to know how to declare variables, assign data to variables, and terminate commands properly.

A variable in JavaScript is an identifier whose value can be retrieved or set and is normally defined with the var keyword. Here is an example of a variable declaration:

var myName;

To actually assign a value to this variable and give it something useful to do, we must use the assignment operator, =. Here is the same statement with a value assigned to the variable:

var myName = "Joseph";

Note

In this instance, we are assigning a string value to the variable. There are many different types of values, or data, that we can assign to variables, and we'll learn more about these in the next chapter.

You will note that we also place a semicolon after each variable declaration, whether we assign a value to it or not. While it is not absolutely necessary to do this, the use of a semicolon in this manner terminates a command. Multiple commands should, however, be placed across multiple lines, as demonstrated here:

var firstName = "Joseph";

var lastName = "Labrecque";

console.log("Hello, " + firstName + " " + lastName);

We assign string values to both a firstName and lastName variable, and then employ the console.log() method along with some string concatenation using the + operator to form a message and output it to the browser console. When executed in the browser, it appears like this:

Figure 2.18: The resulting output message

Note

The term concatenation simply refers to joining plain strings and string variable values together, as we've done here.

That's about all you need to know regarding syntax to get started. Don't worry—there will be much more information around syntax when you reach Chapter 5, Beyond the Fundamentals.

JavaScript Execution Order

This section hearkens back to an example from the previous chapter in terms of the various ways JavaScript can be included within a web document. There are two choices here: either include an external JavaScript file somewhere within the <head> tag or the <body> tag of your HTML document or embed the code directly within the document itself, again at either location.

No matter how you include JavaScript within your HTML document, the web browser will always execute from top to bottom. Any JavaScript within the <head> tag of a document will execute before anything within the <body> tag of the document. Of course, you can compartmentalize blocks of JavaScript code within functions to execute when invoked as well, which effectively gets around this rule in some ways.

Exercise 2.03: Verifying an Execution Order

Let's conduct a small exercise to see whether, for any JavaScript, the <head> of a document will execute before anything with the <body> tag of the document. Let's get started:

  1. In the exercise files for this chapter, you will find a document named order.html. Open this within Visual Studio Code to inspect it. You will see the following HTML code:

    <!doctype html>

    <html lang="en">

    <head>

        <meta charset="utf-8">

        <title>JavaScript Execution Order</title>

    </head>

    <body>

        <h1>JavaScript Execution Order</h1>

        <p>View the browser console to see the effective order of execution.</p>

    </body>

    </html>

  2. You'll notice there is no JavaScript just yet, so let's insert some bits of code in various places for this demonstration. Add the following code beneath the <title> element within the document's <head> tag:

    <script>console.log('Within the HEAD');</script>

  3. Now, add this snippet directly above the <h1> element within the <body> tag of our document:

    <script>console.log('Within the BODY');</script>

  4. Finally, we'll add another line of code just before the <body> tag closes:

    <script>console.log('At the very END');</script>

    The document should now appear as follows:

    <!doctype html>

    <html lang="en">

    <head>

        <meta charset="utf-8">

        <title>JavaScript Execution Order</title>

        <script>console.log('Within the HEAD');</script>

    </head>

    <body>

        <script>console.log('Within the BODY');</script>

        <h1>JavaScript Execution Order</h1>

        <p>View the browser console to see the effective order of execution.</p>

        <script>console.log('At the very END');</script>

    </body>

    </html>

  5. Run this document within your web browser with the developer tools Console view open. You will be able to verify that yes—the code is certainly processed from top to bottom, as we explained:

Figure 2.19: Verification of the execution order

The console.log() command in JavaScript will write any data within parentheses to the console. This is the simplest way of debugging JavaScript, though this will be explored further in the next chapter.

In this section, we've learned about several important fundamentals regarding the structure and syntax of JavaScript—particularly when it comes to the web browser environment.

In the next section, we'll explore other environments in which JavaScript can run.

主站蜘蛛池模板: 乌苏市| 唐海县| 科技| 视频| 三亚市| 土默特右旗| 巴彦县| 沧源| 吉安市| 屏边| 昌黎县| 揭西县| 隆化县| 西平县| 江陵县| 都江堰市| 方正县| 内江市| 合作市| 泰来县| 宁武县| 嵊州市| 大田县| 德兴市| 青阳县| 德江县| 凭祥市| 缙云县| 北安市| 高清| 台中县| 安岳县| 利川市| 偏关县| 江达县| 雷州市| 义乌市| 达日县| 莱州市| 翁牛特旗| 兴安县|