JavaScript Basics

Videos

Examples from Videos

Notes

Javascript Myths

JavaScript is not Java Java is a programming language developed by Sun Microsystems. It is purely object oriented. JavaScript is a scripting language and although there are some syntactic similaries, the two languages are different. JavaScript is not Simple Just because JavaScript is a scripting language, that does not make it a simple language. It has some simple features, and it is not as rigid as a programming language, however it has many complex features.

What is JavaScript for?

JavaScript is it's own language and pieces of code are embedded in HTML documents. By adding JavaScript you can add executable content to your pages. Some things you may be familiar with are mouse-overs (when you place your mouse over an image it changes to something else). JavaScript is not HTML, however, and there are many differences. 


Javascript is case sensitive. In HTML we can get away with using any case, and that is definitaly not the case in JavaScript. Most keywords are lower case. Variables we create can be any case, but it must be consistent. For example, a variable called "Counter" is different from one called "counter". JavaScript is also sensitive to white space, particularly line breaks. 

You can use JavaScript to do many things. It can control the browser by opening new windows, resizing windows, and closing windows. It can adjust the web page you are looking at by adding animation, adjusting content, or changing images. It also interacts well with HTML forms. You can use JavaScript to check the validity of inputs in form fields, change field content, and add features to buttons.
 

JavaScript code, much like other programming languages, is made up of statements which serve to make assignments, compare values, and execute other sections of code. By and large, programmers will already be familiar with JavaScript's usage of variables, operators, and statements. Below is a chart summarizing the main elements of JavaScript grammar. Following, we will look at each element in detail.

Variables Names which refer to a changeable value.
Example: total may be possess a value of 100.
Operators Actors which can be used to calculate or compare values.
Example: Two values may be summed using the addition operator (+); total+tax
Example: Two values may be compared using the greater-than operator (>); total>200
Expressions Any combination of variables, operators, and statements which evaluate to some result. In English parlance this might be termed a "sentence" or even a "phrase", in that grammatical elements are combined into a cogent meaning. 
Example: total=100;
Example: if (total>100) 
Statements As in English, a statement pulls all grammatical elements together into a full thought. JavaScript statements may take the form of conditionals, loops, or object manipulations. It is good form to separate statements by semicolons, although this is only mandatory if multiple statements reside on the same line.
Example: if (total>100) {statements;} else {statements;}
Example: while (clicks<10) {statements;}
Objects Containing constructs which possess a set of values, each value reflected into an individual property of that object. Objects are a critical concept and feature of JavaScript. A single object may contain many properties, each property which acts like a variable reflecting a certain value. JavaScript can reference a large number of "built-in" objects which refer to characteristics of a Web document. For instance, the document object contains properties which reflect the background color of the current document, its title, and many more. For a fuller explanation of the built-in objects of JavaScript, see the section on "Document Object Model".
Functions and Methods A JavaScript function is quite similar to a "procedure" or "subroutine" in other programming languages. A function is a discrete set of statements which perform some action. It may accept incoming values (parameters), and it may return an outgoing value. A function is "called" from a JavaScript statement to perform its duty. A method is simply a function which is contained in an object. For instance, a function which closes the current window, named close(), is part of the window object; thus, window.close() is known as a method.

 
 

Alerts

The alert is one way of doing output in Javascript. You can make an alert pop up on the screen to state something to the user. To do that, you use the syntax:
alert("The text to pop up");
We will do an example of alerts after we have looked at the document model below.
 
 

The Document Object Model

The Document Object Model is a way to refer to and access different parts of an HTML document.

Let's look at some examples:

The code for the above example looks like this:
 
 

<form name=frm1>
        <input type=text name=field1 value="Original Text"><P>

        <input type=button onClick="document.frm1.field1.value='YO!';"
        value="Make the text box say YO!">
 
        <P>

        <input type=button onClick="document.frm1.field1.value='Oh NO!!';" 
        value="Make the text box say Oh NO!!!">
        <P>
        <input type=button onClick="alert('You clicked the button!');" 
        value="Do an alert">
</form>

Notice that we don't just say document.frm1.field1='Yo!'. We have to use the .value extension. This is because the text that shows up in the box is not the field itself; it is one attribute of the field.

Let's look at some of the general syntax in Javascript.

Variables

Variables store and retrieve data, also known as "values". A variable can refer to a value which changes or is changed. Variables are referred to by name, although the name you give them must conform to certain rules. A JavaScript identifier, or name, must start with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). Typically, variable names are chosen to be meaningful regarding the value they hold. For example, a good variable name for containing the total price of goods orders would be total.

scope

When you assign a new variable to an initial value, you must consider the issue of scope. A variable may be scoped as either global or local. A global variable may be accessed from any JavaScript on the page. A local variable may only be accessed from within the function in which it was assigned.

Commonly, you create a new global variable by simply assigning it a value:

newVariable=5;

However, if you are coding within a function and you want to create a local variable which only scopes within that function you must declare the new variable using the var statement:

function newFunction()
{ var loop=1;
  total=0;
  ...additional statements... 
}

In the example above, the variable loop will be local to newFunction(), while total will be global to the entire page.

type

A value, the data assigned to a variable, may consist of any sort of data. However, JavaScript considers data to fall into several possible types. Depending on the type of data, certain operations may or may not be able to be performed on the values. For example, you cannot arithmetically multiply two string values. Variables can be these types:
Numbers 3 or 7.987, Integer and floating-point numbers.
  • Integers can be positive, 0, or negative; Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.
  • A floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").
Booleans True or False. The possible Boolean values are true and false. These are special values, and are not usable as 1 and 0. In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true.
Strings "Hello World !" Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.)
Objects myObj = new Object();
Null Not the same as zero - no value at all. A null value is one that has no value and means nothing.
Undefined A value that is undefined is a value held by a variable after it has been created, but before a value has been assigned to it.

That said, JavaScript is a loosely typed language -- you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. By and large, you may simply assign any type of data to any variable. The only time data typing matters is when you need to perform operations on the data. Certain operators behave differently depending on the type of data being deal with. For example, consider the + operator:

"5" + "10" 
yields
"510" (string concatenation)
5 + 10 
yields
15 (arithmetic sum)

 

Statements

Statements define the flow of a script, known as "program flow." A statement, like a fully grammatical English sentence, is made up of smaller expressions which, altogether, evaluate into a cogent meaning. In JavaScript, statements are organized as either conditionals, loops, object manipulations, and comments.

JavaScript statements should be terminated with a semicolon (;).

A set of statements that is surrounded by curly braces ({ and } ) is called a block. Blocks of statements are used, for example, in functions and conditionals.

Normally statements are executed sequentially: x = 1; y = 2; z = x + y; but this can be altered by some statements which test a condition and branch or loop according to the result.

Comments

Despite the fact that comments are purely optional, they can easily be a crucial part of your program. Comments can explain the action, like a color commentary, which can be a great help in understanding the code. Whether as a teaching tool or to simply remind yourself what the code does, comments are best sprinkled liberally throughout a program. Remember, comments are for humans, so write them that way!

Comments can also be used for debugging -- you can comment out sections of code to prevent them from being executed. In doing so you may learn more about why a certain problem is occurring in your program.

Because JavaScript must ignore comments, there is an appropriate syntax for demarcating text as a comment. For single line comments, simply precede the line with two forward slashes. For multi-line comment blocks, begin the comment with /* and close with */.

//A lonely ol' single line comment
/* A dense thicket of commentary, spanning many captivating lines
of explanation and intrigue. */