JavaScript Introduction

Updated 7/13/2018 at 7:50pm

What Javascript Is

Javascript:

Here is some explanation about each of the above points:

Javascript is built into your Web browser.

Netscape incorporated Javascript into their browser first, but Internet Explorer was not far behind. The "engine" that runs the Javascript code in a Web page is built into the browser. When a page loads into the browser, the browser runs (executes) any Javascript code it finds in the page that is not in a function (more on that later), and it stores any function code in the browser's memory for later usage.

Javascript can be used anywhere in your Web page.
Javascript is a programming language.

More specifically, Javascript is a symbolic programming language, which means that you use symbols (names) to tell the browser to do something to or in the page that it is displaying. You use symbols called "variables" to name memory storage areas. You use symbols called "functions" to store code in a handy place in memory, that you can run later in response to an event such as a mouse click, or a mouse-cursor rollover. You use symbols called "operators" to do logic and math calculations or to combine variables into other variables, etc.

Javascript is object oriented.

A general definition of an object is that it is a thing. In programming, this definition still holds; in programming, this thing called an object contains stuff. The "stuff" that an object contains is variables and functions, and sometimes other objects. As I noted above, variables hold information for later use. Functions hold code that can be run later in response to an event. (Technically, a function contained by an object is called a "method", and a variable contained by an object is called a "property". We'll see more about that later, too.)


What Javascript can do:


[OPTIONAL -- for users of the Internet Explorer browser]

*IMPORTANT* - Some IE settings need to be changed!!

Please note: If you are using Internet Explorer 7 or above, you will probably need to enable some JavaScript features in order for the examples in these handouts, and for your assignment pages, to run.

Follow these steps:

  1. Click the "Tools" top menu item.
  2. Click "Internet Options".
  3. Click the "Security" tab.
  4. Click the "Custom level..." button.
  5. In the "Scripting" section, toward the bottom of the list, enable these items:
    • "Active scripting"
    • "Allow status bar updates via script"
    • "Allow websites to prompt for information using scripted windows".
  6. Click the "Advanced" tab.
  7. In the "Browsing" section, make sure these settings are set:
    • Uncheck "Disable script debugging" (both lines).
    • Check "Display a notification about every script error".
  8. In the "Security" section, make sure these settings are set:
    • Check "Allow active content to run in files on My Computer".
  9. Click "OK", etc.

Basic Syntax

"Syntax" means "the way in which words and symbols are combined to make correctly-formatted code."

Here is a sample of an HTML page with some Javascript code in it:

<!DOCTYPE html>
<html>

<head>
  <title>JavaScript Syntax</title>
  <meta charset="UTF-8">
  <script type="text/javascript">
    /* <![CDATA[ */
    // say hello world!
    alert("Hello world from the <head> section!");
    // Javascript can go here, but no raw HTML!
    /* ]]> */
  </script>
  </head>
  
  <body>
  
  <h1>This is a JavaScript Sample.</h1>
  
  <script type="text/javascript">
    /* <![CDATA[ */
    // Put an <h3></h3> tag into the page:
    document.write("<h3>Basic JavaScript Syntax</h3>");
    // Javascript can go here, but no raw HTML!
    /* ]]> */
  </script>
  
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Variables

When the JavaScript code in your page is "running" (meaning that the JavaScript processor that is built into the browser is processing the JavaScript instructions), you usually need to give the JavaScript processor a place to store information in the computer's memory. You give JavaScript a place to store information by using variables. A variable is a named (meaning that you give it a name) memory-storage item.

Variables:


Keywords

Certain symbols (words) in Javascript are called keywords because they are reserved for key (important) operations and statements. You should never use these keywords as variable or function names. A partial list of these keywords follows:


Operators

Operators are used in JavaScript statements (see below) to connect and/or do things with the variables, functions, objects, and literals in those statements.

The most basic, and most common, operator in JavaScript is the assignment operator.

The Assignment operator in Javascript is the equal sign.

The equal sign ( = ) in Javascript means "is assigned the value of", or "receives the value of". It does not mean "equals" as in algebra. (There is a way in JavaScript to compare values for equality, but we will see the "equality" operator later.)

For example, if you want to assign the value 5 to a variable called myFirstVar, you do it like this in Javascript:

  var myFirstVar = 5;
Please note these points about the above code:

Arithmetic operators are used to do math (numeric) calculations.

Arithmetic operators in Javascript:


The Concatenation Operator

You can "add" strings (see below) in JavaScript with the concatenation operator, which is the plus sign (+). "Concatenation" means putting two pieces together to make a single entity.

(JavaScript uses the context of the plus sign to determine whether + is being used for numeric addition or string concatenation. More on this feature later.)


Strings

Javascript strings are any series of text characters between quotes. For example, Javascript can store my name in a variable as a string if I use code something like this:

  var nameVar = "Jim Link";
Please note these points about the above code:

Statements

Statements are how you give instructions to the JavaScript processor.


Curly Braces (code groups)

You will often see curly braces ( { and } ) in Javascript code. Curly braces are used to group several statements into a single block (unit) of code. Here is an example:

  if (nameVar == "Jim Link")
  {
    alert("Hi!");
    alert("There!");
  }
Please note these points about the above code:

Built-in Functions

Functions are named (recall that Javascript is a symbolic programming language) units of code (and are also called "methods" when they are contained in an object -- more on that later) that do something (meaning, they run one or more statements) and then optionally return a value of some kind. We will see how you can write your own functions later in the course. For now, you need to know that Javascript has many built-in functions/methods (which means that they come "free" with your browser and are ready to use).

Functions/methods process information. All function names look like functionName() or FunctionName() or functionname(). The main thing to note is that the function's name is followed by a set of parentheses. There may or may not be something between the parentheses, depending on the function. But the parentheses must be there!

If there is something inside the parentheses, what is in the parentheses is called arguments. There may be none, one, or multiple arguments. If there are multiple arguments, they are separated by commas. Arguments are how you send information (in the form of variables or literals) into the function.


One handy built-in method is alert(). You saw alert() in the first sample. The alert() method can be used for displaying information to the user, or for debugging your Javascript code by displaying the value of a variable, for instance.


Another one of Javascript's built-in methods is document.write(). This method inserts into the HTML page, at the place where the statement is located, whatever is in the parentheses, which is usually a string literal or string variable. This method can also be written as window.document.write(). (We'll talk about the Document Object Model (DOM) more in a future class, but for now just keep in mind that JavaScript has a "window" object and a "document" object, and that the "document" object is contained in the "window" object. The periods in the statement "window.document.write()" tell JavaScript that the write() method is contained in the document object, and that the document object is contained in the window object.)


Another handy built-in method is prompt(). The prompt() method asks the user for some information and then puts that information into a variable that you specify.


Here is some sample code that uses some of these built-in methods:

<!DOCTYPE html>
<html>
<head>
<title>A Form Letter</title>
<script type="text/javascript">
  /* <![CDATA[ */
  var the_name = prompt("What's your name?", "Type your name here");
  /* ]]> */
</script>
</head>
<body>
<h1>Dear
<script type="text/javascript">
  /* <![CDATA[ */
  document.write(the_name);
  /* ]]> */
</script>,</h1>
Thank you for coming to my Web page.
</body>
</html>
You can see the above code running here.


Here is some more sample code that uses a lot of these concepts:

<!DOCTYPE html>
<html>
<head>
<title>Seconds in a Day</title>

<script type="text/javascript">
  /* <![CDATA[ */
  var seconds_per_minute = 60;
  var minutes_per_hour = 60;
  var hours_per_day = 24;
  
  var seconds_per_day = seconds_per_minute * minutes_per_hour * hours_per_day;
  /* ]]> */
</script>
</head>
<body>

<h1>My calculations show that . . . </h1>

<script type="text/javascript">
  /* <![CDATA[ */
  var first_part = "there are ";
  var last_part = " seconds in a day.";
  var whole_thing = first_part + seconds_per_day + last_part;
  
  window.document.write(whole_thing);
  /* ]]> */
</script>

</body>
</html>
You can see the above code running here.

Please note these points about the above code:

Back in the class on CSS, you saw how you could use document.write() to put a different style sheet in your page depending on the browser that the user is viewing your page with. Here is that code again:

<!DOCTYPE html>
<html>
  <head>
  <title>Test of Netscape vs. IE for Style Sheets</title>
  <script type="text/javascript">
    /* <![CDATA[ */
    var browserName=navigator.appName;
    var browserVer = parseInt(navigator.appVersion);
    var version = "";

    if ((browserName=="Netscape") && (browserVer>=4))
      version="Net4";
    else if ((browserName=="Microsoft Internet Explorer") && (browserVer>=4))
      version="IE4";
    else
      version="other";

    if (version == "IE4")
    {
      document.write("<link rel='stylesheet' type='text/css' href='IEExternal.css'>");
    }
    else if (version == "Net4")
    {
      document.write("<link rel='stylesheet' type='text/css' href='NetExternal.css'>");
    }
    else
    {
      document.write("<link rel='stylesheet' type='text/css' href='OtherExternal.css'>");
    }
    /* ]]> */
  </script>
  <noscript>
    <link rel="stylesheet" type="text/css" href="OtherExternal.css">
  </noscript>
  </head>
<body>
  <!-- (The main HTML page content goes here...) -->
</body>
</html>

Please note these points about the above code:


Built-in Objects

Some functions (which are called methods when they are contained by an object) can only be used after you create the object that contains that function/method.

One such object in Javascript is the Date() object. Note that the name is capitalized. You create a new Date object like this:

var now = new Date();
Note the new keyword. It tells Javascript to create a new object, in this case an object of the Date type.

After the new object is created, you can use its built-in functions (methods) to do things with it. Please note that the Date() object contains both date and time information from the client (browser) machine's local clock. There are methods in the Date() object that allow you to obtain both date and time information.

Here is some sample code that uses some of the Date() object's methods:

<!DOCTYPE html>
<html>
<head>
<title>Write the Date</title>
<script type="text/javascript">
  /* <![CDATA[ */
  // get the date information
  var today = new Date();
  var the_day = today.getDate();
  var the_month = today.getMonth();
  var the_year = today.getFullYear();
  var hours = today.getHours();
  var minutes = today.getMinutes();
  var seconds = today.getSeconds();
  
  // correct for the month starting from zero
  the_month = the_month + 1;
  
  // create the string you want to print
  var the_whole_date = the_month + "/" + the_day + "/" + the_year;
  var the_whole_time = hours + ":" + minutes + ":" + seconds;
  
  /* ]]> */
</script>
</head>
<body>
Today's date is:
<script type="text/javascript">
  /* <![CDATA[ */
  // write the date:
  document.write(the_whole_date);
  // put in a break tag:
  document.write("<br>");
  // write some text:
  document.write("The time is: ");
  // write the time:
  document.write(the_whole_time);
  /* ]]> */
</script>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Properties and Methods

By way of summarizing a lot of what you have read in the previous sections of this handout, let me say that objects contain variables, which are called "properties" of the object. Objects also contain functions, which are called "methods" of the object. See the table below for a visual explanation of what Javascript has in it:

Variables contain information.
Functions contain instructions that respond to events and which manipulate the values in Variables.
Objects contain Variables and Functions, which are called Properties and Methods; and sometimes even contain other Objects.
Operators connect variables and functions (properties and methods) by performing various operations.

Javascript properties and methods are associated with the object that they belong to, with what is called dot notation. For example, the document.write() built-in function (which we discussed somewhat in a previous section) is actually a method of the document object. The dot (or period) between document and write() makes the phrase document.write() actually say something like this: "the write() method which belongs to the document object", or "the document object contains the write() method".


Javascript Warning

It is possible for the user to turn off Javascript processing in their browser. If the user has turned off Javascript processing, you have a choice of what to do about it:

  1. Ignore it and frustrate the user
  2. Ask the user to turn on Javascript processing

In the hopes that you will choose the more reasonable and helpful of these two options, here is some code that you can put in your page to ask the user to turn on their browser's Javascript processing:

Simply put, you will use the <noscript>...</noscript> tag in your page. The noscript tag's content is displayed by the browser wherever it falls in the source code, but only if the user has turned off Javascript processing. For older browsers, and those browsers that don't support scripting, the noscript tag is ignored completely.

Now, here is a code sample:

<!DOCTYPE html>
<html>
<head>
  <title>Noscript Sample</title>
</head>

<body>
<h3>A sample of <noscript></h3>

<noscript>
  <div style="color:red;">
  <p>
    This document requires that you turn on Javascript processing in your browser.
  </p>
  <p>
    Please follow these instructions to turn on scripting in your browser:
  </p>
  <p>
    <u>Firefox 3+</u>
  </p>
  <ol>
    <li>Choose "Tools", "Options...", "Content" tab</li>
    <li>Click "Enable JavaScript"</li>
    <li>Click "OK"</li>
    <li>Click on the Reload button in the toolbar</li>
  </ol>
  <p>
     <u>Chrome 20+</u>
  </p>
  <ol>
     <li>
        Click on the "wrench" icon in the upper right part of the window.  This
        icon opens the "Settings" tab.
     </li>
     <li>
        Click the link "Show advanced settings..." at the bottom of the page.
     </li>
     <li>
        Look for the "Privacy" section and click on the "Content settings..." button.
     </li>
     <li>
        Click on the radio button next to "Allow all sites to run JavaScript (recommended)"
     </li>
     <li>
        Click the "OK" button.
     </li>
     <li>
        Close the "Settings" tab.	
     </li>
  </ol>
  <p>
    <u>Microsoft Internet Explorer, 5+</u>
  </p>
  <ol>
    <li>Choose "Tools", "Internet Options...", "Security" tab, "Custom Level...", 
      "Scripting"</li>
    <li>Click to "Enable" Active scripting.</li>
    <li>Click "OK"</li>
    <li>You will probably have to refresh the page</li>
  </ol>
  <p>
    <u>Netscape Communicator 4+</u>
  </p>
  <ol>
    <li>Choose "Edit", "Preferences", "Advanced"</li>
    <li>Click "Enable JavaScript"</li>
    <li>Click "OK"</li>
    <li>Click on the Reload button in the toolbar</li>
  </ol>
  </div>
</noscript>
</body>
</html>
And here's what this code would look like in your page if the user has scripting turned off:

This document requires that you turn on Javascript processing in your browser.

Please follow these instructions to turn on scripting in your browser:

Firefox 3+

  1. Choose "Tools", "Options...", "Content" tab
  2. Click "Enable JavaScript"
  3. Click "OK"
  4. Click on the Reload button in the toolbar

Chrome 20+

  1. Click on the "wrench" icon in the upper right part of the window. This icon opens the "Settings" tab.
  2. Click the link "Show advanced settings..." at the bottom of the page.
  3. Look for the "Privacy" section and click on the "Content settings..." button.
  4. Click on the radio button next to "Allow all sites to run JavaScript (recommended)"
  5. Click the "OK" button.
  6. Close the "Settings" tab.

Microsoft Internet Explorer, 5+

  1. Choose "Tools", "Internet Options...", "Security" tab, "Custom Level...", "Scripting"
  2. Click to "Enable" Active scripting.
  3. Click "OK"
  4. You will probably have to refresh the page

Netscape Communicator 4+

  1. Choose "Edit", "Preferences", "Advanced"
  2. Click "Enable JavaScript"
  3. Click "OK"
  4. Click on the Reload button in the toolbar