<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> JavaScript Language Fundamentals
<resources>
  spacerspacer

JavaScript Language Fundamentals

Placing JavaScript: JavaScript code is usually placed inside HTML <script> tags. Inside the <script> tags, the rules of JavaScript apply. No raw HTML can go directly inside the script tag once created. <script> tags containing JavaScript are frequently placed in the frequently in the <head> tag, as this is not a visible area of an HTML document. Placing JavaScript in the <head> tag can keep our page from looking messy when we are trying to work with the design.

On occasion, we'll find JavaScript embedded directly in the value section of a special HTML attribute called an event handler. Here's an example:

<img src="mypic.jpg" onmouseover="rollit()" />

In the above example we have an attribute named onmouseover. It responds to the user placing their mouse over the image while viewing the page. Above we have placed a custom JavaScript function named rollit() inside the attribute. We can therefore place JavaScript code on a page without script tags.

Later we'll place JavaScript we wish to use on multiple pages inside a JavaScript Include File

Script Tags: The format of a typical JavaScript inside <script> tags starts with this:

<script type="text/javascript">

//Code goes here

</script>


Above there is no exectuable code, only a comment tag (//Code goes here) inserted in the text. The double slashes indicate no code will be executed beyond that point on the line. We can also use CSS style comment tags for multiple lines of comments:

/*
This is a multi-line
comment
*/

Built-in JavaScript Functions: In JavaScript we have been provided with numerous built in functions which are commands created to give us access to pieces and parts of the browser and perform actions. For example:

alert("I'll Pop Up In a Window!");

If the above code is placed inside the <script> tags from the previous section, you'll see a message pop up and take control of the screen. This effect of forcing you to click or react is called a modal window.

Note the presence of the parentheses () after the keyword alert. The parens are a required part of a function in JavaScript and in many other programming languages.

JavaScript Statements: JavaScript expects us to speak to it in lines of code it understands, called statements. Each JavaScript statement typically go on one line of text, and most end with a semi-colon:

alert("This creates a message that pops up into a modal window!");

The semicolon indicates the end of the statement, which is then executed one line at a time, or until it finds an error, in which case most browsers stop processing your code.

Data Types:
There are 3 basic types of data in JavaScript, strings, numbers and booleans.

Numerical data for purposes of doing math is entered in JavaScript without quotations around it, while alphanumeric data (hereafter called string data) needs to be inserted within quotes. Booleans are not quoted and can contain only the values true or false (lower case). Booleans are used to test conditions.

While the JavaScript engine is processing, it will give it's best guess as to the data type involved. In general, any number that can be used in a calculation is considered numerical. An address number, like a zip code, would be a string.

Since JavaScript can change the data type based on circumstances, we can say JavaScript is a loosely typed language, just as other scripting languages (PHP, ActionScript, VBScript). Scripting languages read and process our code on the fly, while compiled languages (Such as C, C# and Java) compile code into another form that will run more quickly.

String Data: In JavaScript (and in nearly all programming languages) data stored in quotes are called strings, chiefly because they consist of a series of alphanumeric characters stuck together like beads on a string. The data inside a string is an unknown to the program, but assumed to be understood by the users involved. In the case of JavaScript, HTML can be embedded in a string and passed off to the browser to be written to the page. JS therefore can pass HTML embedded in a string but be entirely unaware of what type of content it is passing.

When we built our alert() function above, we provided a string of data inside the parens to indicate what to say when we did our popup:

alert('Say something clever!');

Single vs Double Quotes: Quoted strings in JavaScript can be contained inside either be single or double quotes, but we need to start and end with the same type of quote. We'll switch back and forth between single and double quotes for convenience or as the need arises. Since HTML frequently uses double quotes, we'll frequently use single quotes instead to be sure JS is not surprised by the quotes inside the string data.

Escape Characters: When we have string data that uses the same type of quote we are using to indicate the beginning and end of a string, we must escape the extra quote, as JavaScript will try to interpret the quote as the end of the string and throw an error. For example:

alert('My name is O\'Malley!);

The backslash above is in front of the single quote just before after the capital "O" in O'Malley. Placing the backslash directly in front of the added third quote tells JS to ignore the quote as a special character and treat it as part of the string. This allows the code to run error free.

Numerical Data: JavaScript can work with numbers of various types (integer, floating point, etc.) but when use typeof() to determine what type of data we have in action in our script:

alert(typeof(5));

Using typeof() with numerical data usually returns the string Number in instances like the above. typeof() is actually an operator not a function as it appears to be above. In fact, typeof() is said to be of limited use in programming as the information attained this way is untrustworthy: typeof considered useless

Variables: Variables are programming constructs that can store data that 'varies' or is changeable. In JavaScript not even the type of data is a certainty. However we can declare a unique name and immediately assign data to it, for example our name:

myName = "Bill";
alert(myName);

In the above example, the string consisting of the letters B-i-l-l is stored in a variable named myName. Once the data is stored in the variable, it is available to be used programmatically by JavaScript. If the variable is created directly in our procedural code, the variable is available everywhere on the page until we do something to disturb this availability.

Variable Scope: In programming, the word scope refers to the availability of a variable as regards the rest of our program or page.

Global Scope by Default: In JavaScript, anytime a variable is created outside of functions or classes the variable is said to have global scope. Global means it's available everywhere, inside all classes and functions. This is NOT the usual behavior for programming languages and is considered dangerous. The reason why is that what if we both contribute functions to a project and create global variables, the data in our functions could contaminate each other and change data.

We'll find out in a demonstration momentarily in JavaScript we can equate global level scope to window level scope!

Using var To Force Local Scope: If we create a variable inside a function, it is also a global variable unless we declare the variable with the keyword var in front of it:

var myName = "Steve";

Using the keyword var in front of a variable declared in a function forces it to be local instead of global. Here's an example to study to see how variables react in different scopes: variable scope example

Operators: JavaScript uses operators which allow us to make mathematical calculations, and also to concatenate (connect) strings of data. Many of the operators we are familiar with from our math days exist (the plus sign, minus sign, etc.) plus several more. We'll find that some operators look familiar but do different things (and double duty) based on the context in which they are used.

myVar = 2 + 2;

In the above example the plus sign is the operator that allows us to add 2 and 2. The equals sign allows us to assign the data on the right hand side of the equals sign to the variable on the left. We'll say that

Programs Read Right To Left: The equals sign as used above does not mean that data is the same on both sides of the equals sign like an algebra equation. We cannot "flip" a programming statement and read it left to right. We must always read right to left when working with any programming language. Therefore the equals sign always assigns data from the right into some mechanism on the left. We therefore call the equals sign the assignment operator. Later we'll find out that operators can be connected together to create new compound operators for other purposes. One such operator consists of two connected equals signs. This operator is called the comparison operator, because it is used to compare both sides of the operator.

Concatenation: String data can be connected together (concatenated) using the plus sign:

myName = "Bill " + "Newman";

Note the space left after the first name and in front of the second double quote. The space is placed to ensure the two words have a space between them, once they are concatenated.

Conditionals: JavaScript allows us to do different things according to different circumstances. We do this as people, when we say:

If it rains, bring an umbrella. Otherwise, bring shorts.

A ‘conditional’ is a statement that allows us to determine what happens “if” something occurs. The most common conditional in most programming languages (including JavaScript) is the if statement.

If Statement: In JavaScript we can branch our code and do different things by checking to see if a value equates to the boolean value of true in an if statement. We check the value inside of a pair of parens, and then execute the code inside a set of curly braces that immediately follow the parens only if what is inside the parens equates to a true statement. Here is a sample if statement:

if(x == y)
{
alert("I guess x equals y!");
}


The double equal sign is the operator that checks for equality. If the variables x and y are equivalent, then the alert displays. If x does not equal y above nothing occurs. We call the double equal sign the comparison operator.

if/else: The logic above works great, as long as we only want to see an alert if the two values are equal! However this is perhaps less then visually appealing. Therefore we'll use a variation on the if statement called if/else:

if(x == y)
{
alert("I guess x equals y!");
}
else{
alert("I guess x and y are NOT equal!");
}

Booleans: The boolean data type gets its name from the mathematician George Boole. Boolean data consists of logic types. For us, that would be the values true and false. Boolean data, like numerical data, does NOT use quotation marks. Booleans (true or false) are always lower case:

If(x == true){alert("It's true!!");}

We use booleans as a flag to test conditions. Some JavaScript functions return a boolean to let us know if what we were asking was true or not.

The Not Equal Operator: Another important operator, often associated with Booleans, is the not equal operator, symbolized by the exclamation mark and the equal sign !=

The not equal operator is used with the equal sign to identify the values in the if statement are not equivalent and therefore evaluate to false:

If(x != true){alert("That would be false!");}

Compound Operators: There are a few other operators you'll see, and some are very powerful. We call them compound operators because it takes at least two characters to represent them. We've already seen a couple of them, the double equal sign (comparison) and the not equal sign !=.

Append Operators: There are a set of operators that we'll call the append operators. We call them this because they add, connect or effect the variable on the left while using the contents of the variable as part of an equation. Let's say we wish to store data in a string, then append more string data to it:

myName = "Bill";
myName = myName + " Newman";

The above example works, meaning the variable myName stores the string "Bill Newman". However it looks odd because we had to place the variable myName on both sides of the equal sign. We can shorten this line of code by using the concatenation append operator, +=:

myName = "Bill";
myName += " Newman";

The example above does the same thing as the previous example, but with less code. We can also use the plus equals operator to add to an existing example. Here is an example of adding number data to variable:

myTotal = 2;
myTotal +=2;

Below we have added an additional 2 to the original variable, and now the total stored is 4. ACll of the other mathematical operators have

Increment Operator: Another compound operator is the incremental operator. We can use a special operator ++ to increment (add one) to an existing variable:

myTotal = 2;
myTotal
++;

After the above line of code is executed, myTotal is 3.

Decrement Operator: The opposite of incrementation (adding one) is decrementation, which uses the -- operator:

myTotal = 2;
myTotal
--;

After the above line of code is executed myTotal is 1.

Built In JavaScript Objects: JavaScript has a few built in objects such as Date(), Math(), String() and Number(). Each of these objects is designed to give us greater control over data or resources like the system clock on a user's machine.

Date() Object: JavaScript's Date() object gives us access to a running instance of the system clock of the user’s machine:

var myDate = new Date();

We need to create an instance (example) of a date object in order to use it further. This allows us to work with different date objects at once.

Once we have an instance of the Date() object running in memory, we can use the date object to examine pieces and parts of the data it provides:

alert(myDate.getHours());

In the above example, our Date() object (named myDate) is examined to return the current hours via a method provided by the Date() object named getHours(). A method is like a function, but it is associated with a specific object. There are many pieces of data we can extract from our Date() object in this way. View the following web page that shows Methods & Properties of the Date() object

Time Customization: Users come to our website from different parts of the world. Accessing the user’s system clock is useful for tailoring a user’s experience to their time of day.

What if you wanted to show a custom image or message based on the time of day of the user? JavaScript and the Date() object provide this capability. The sample below accesses the date object on the user's machine, and displays an alert(), if it’s noon, or later:

var myDate = new Date();
If(myDate.getHour() > 12)
{
alert("It's after Noon!");
}

In fact, this technique is part of an assignment for this class! View the examples page to see how this can be done: examples page

JavaScript Object Reference: JavaScript has other built in objects besides the Date() object. Here's a reference to other JavaScript Objects

Custom JavaScript Functions: We saw previously that JavaScript provides plenty of functions that are built in. However we can create our own custom JavaScript functions that incorporate our own code and even other functions, built in or custom!

When we build a custom function, we want to name it in a way that we (and everyone else) knows what it does. To create the function, we use the keyword, function, our name, a pair of parens and a pair of curly braces:

function myNewFunction()
{

//create custom function code here

}

The function above doesn't actually do anything yet, so we can call it a stub. However it will not throw an error and we can use it as a starting point for creating our new function. Let's build a function that will something dramatic like change the background color of the current document:

function changePageColor(newColor)
{//pass in a string of data to represent a color and change the background color of the page

document.bgColor=newColor;

}

The function above can change the background color of the page via a property of the document object named bgColor. We'll learn more about the document object and properties in the BOM lesson.

The function expects a string of data to be passed in to it, and the function will take the string of data and create a new variable in our case named newColor and copy the data from the outside world into the function. Then the newColor variable is assigned to the document.bgColor property and the entire page color changes!

Function Placement: Think of functions as a set of instructions to be run only when they are called. For example, like the plays in a football play book. To be put in play, the name of the function must be called by you the developer. If you call a function, it must be within scope (be declared and available) to the JavaScript on the current page. For a function to be within scope you can place the function anywhere on the current page and even inside a separate JavaScript include file! This is because JavaScript (like nearly all programming languages) read the instruction set of all functions and classes into memory before executing each line of JavaScript you write in sequence. Therefore I like to say that functions and classes are out of flow with your procedural (sequential) JavaScript commands!

Functions Hidden Out Of Flow: Since we think of functions as "out of flow" and read into memory before our sequential code is executed, we can hide functions in out of the way places. If we have a single page, functions are frequently placed at the bottom of the sequential code inside our <script> tags. When we have several functions that we would like to use in various pages, we can create a JavaScript include file to store them and then call the include file before we work with our sequential code.

Here is Dustin Diaz's list of his Top Ten Custom Functions

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved