Course notes 13
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Review of Javascript

February 15th, 2011

  1. Javascript Variables & Variable Concatenation
  2. Javascript Functions



Javascript

JavaScript is a cross-platform, object-oriented scripting language.

• JavaScript is case sensitive; letters include both the uppercase and lowercase characters.

Netscape invented JavaScript.

Javascript building blocks:

1) Types of values:

• numbers (integers or floats) - 42 or 3.14159
• Boolean values - TRUE or FALSE
• strings, such as "Javascript"

String data is placed between quotations, numbers and Booleans are not.

• null - absence of a value.
• undefined - value used when a variable is declared, but not yet initialized (assigned a value).

2) Data Conversion - In Javascript, you do not have to specify a variable's data type, i.e., string, Boolean, etc. If two variables of different data types are combined, Javascript performs data conversion when necessary. In other words, it switches one of the variables' data types to match the other variable.

• var answer = 42 (this line declares a variable called: answer and initializes it to the number value: 42)

• answer = "Thanks for all the fish..." (later in the code, we can re-initialize the variable answer to equal a string. In some languages this would cause an error, but not in javascript.)

• In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings:

x = "The answer is " + 42 // returns "The answer is 42"
y = 42 + " is the answer" // returns "42 is the answer"

3) Variables - symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

• Identifiers must start with a letter, underscore (_), or dollar sign ($) - ( $ is common in PHP); subsequent characters can also be digits (0-9). DO NOT begin a variable name with a number!

• Examples of usable variable names include: Number_total, $name, _temp1. I highly recommend using naming conventions to make your code easier to read and easier to remember what you were trying to accomplish.


A) Declaring Variables - you can declare a variable in two ways:

• By simply assigning it a value. For example, x = 42. Javascript will automatically recognize the data type by the value you give a variable.

• With the keyword var. For example, var x = 42.

B) Evaluating Variables - if a variable has not been initialized, Javascript has to evaluate the unassigned variable, and that depends on how it has been declared:

• If the unassigned variable was declared without var, the evaluation results in a runtime error - meaning your program/scripts won't work.

• If the unassigned variable was declared with var, the evaluation results in the undefined value.

• Undefined value behaves as false when used as a Boolean value.

• Null value behaves as 0 in numeric contexts and as false in Boolean.

C) Variable Scope - global and local.

• Global variables are declared outside of a function and thus available throughout the program, i.e., all functions recognize and call a global variable.

• Local variables are declared within functions and are only available within that particular function. Other functions do NOT recognize another function's local variables and cannot call them.

• You do not have to use var to declare a global variable, but it is necessary for a local variable.

D) Expressions - any valid set of literals, variables, operators, and expressions that evaluates to a single value; the value can be a number, a string, or a logical value.

• Arithmetic: evaluates to a number, for example 3.14159
• String: evaluates to a character string, for example, "Fred" or "234"
• Logical (boolean): evaluates to true or false

E) Operators - Javascript contains a variety of operators, which are used in the evaluation of an expression, i.e., +, *, ==, etc.

• Assignment Operators - assign a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.

• Shorthand for assignment operators:

x += y same as x = x + y

x -= y same as x = x - y

x *= y same as x = x * y

x /= y same as x = x / y

x %= y same as x = x % y


• Comparison Operators - compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values.

Equal (==)  
Returns true if the operands are equal. If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.  
3 == var1
"3" == var1
3 == '3'

Not equal (!=)  
Returns true if the operands are not equal. If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.  
var1 != 4
var2 != "3"

Greater than (>)  
Returns true if the left operand is greater than the right operand.  
var2 > var1

Greater than or equal (>=)  
Returns true if the left operand is greater than or equal to the right operand.  
var2 >= var1
var1 >= 3

Less than (<)  
Returns true if the left operand is less than the right operand.  
var1 < var2

Less than or equal (<=)  
Returns true if the left operand is less than or equal to the right operand.  
var1 <= var2
var2 <= 5


• Arithmetic Operators - take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages, except the / operator returns a floating-point division in JavaScript, not a truncated division as it does in languages such as C or Java. For example:

1/2 (returns 0.5 in JavaScript)
1/2 (returns 0 in Java)

• Other Arithmetic Operators:

%
(Modulus) - Returns the integer remainder of dividing the two operands.

Ex: 12 % 5 returns 2.  

++
(Increment)  - Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.  

Ex: If x is 3, then ++x sets x to 4 and returns 4, whereas x++ sets x to 4 and returns 3.  

--
(Decrement) - Subtracts one from its operand. The return value is analogous to that for the increment operator.  

Ex: If x is 3, then --x sets x to 2 and returns 2, whereas x++ sets x to 2 and returns 3.  


• Logical Operators - typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

&& (expr1 && expr2)
(Logical AND) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.  

|| (expr1 || expr2)
(Logical OR) Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.  

! (!expr)
(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.  

• Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator:

a1=true && true                     // t && t returns true
a2=true && false                    // t && f returns false
a3=false && true                    // f && t returns false
a4=false && (3 == 4)             // f && f returns false
a5="Cat" && "Dog"                // t && t returns Dog
a6=false && "Cat"                 // f && t returns false
a7="Cat" && false                 // t && f returns false

The following code shows examples of the || (logical OR) operator:

o1=true || true               // t || t returns true
o2=false || true              // f || t returns true
o3=true || false              // t || f returns true
o4=false || (3 == 4)       // f || f returns false
o5="Cat" || "Dog"          // t || t returns Cat
o6=false || "Cat"            // f || t returns Cat
o7="Cat" || false            // t || f returns Cat

The following code shows examples of the ! (logical NOT) operator:

n1=!true              // !t returns false
n2=!false             // !f returns true
n3=!"Cat"            // !t returns false

Short-Circuit Evaluation - as logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

• false && anything is short-circuit evaluated to false.

• true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

• String Operators - in addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example, "my " + "string" returns the string "my string".

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha," then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.


Javascript Variables & Variable Concatenation

Concatenation: the operation of joining two or more character strings end to end.

To join two strings together, we use the + (plus) symbol.
<head>
      <script>
            var name = "John" + "Doe";
            alert(name);
      </script>
</head>

This will alert "JohnDoe".

It's a little pointless to concatenate to non-variable strings together, as you could just do this:
var name = "John Doe";

Usually concatenation is used when you have variables:
var first = "John";
var last = "Doe";
var name = first + " " + last;
alert(name);
This will echo "John Doe";


You can also add strings to the end of a variable with "+=":
var sentence = "John Doe";
var sentence += " is so awesome!";
alert(sentence);

This will echo "John Doe is so awesome!";


Functions

Description:

A function contains code that can be executed by an event or by a call to the function. Functions are often used when you need to do something more than once, with the same or similar results.


The Code:

<head>
      <script type="text/javascript">
            function myAlert(msg) {
                  alert(msg);
            }
      </script>
</head>

<body>
      <a href="#" onmouseup="myAlert('test');">Alert "test"</a><br />
      <a href="#" onmouseup="myAlert('pizza');">Alert "pizza"</a>
</body>


Explanation:

First we create a Javascript function called "myAlert" (you can call it whatever you'd like).
A function always starts with "function", then a space, then the name of the function.

After the function name, you must always have an open and closed parentheses.
Although you don't NEED anything in the parentheses, in this case, we'd like to pass our function a variable. To do so, we must include the name of our variable between the open and closed parentheses. Our variable is called "msg".

After the parentheses, we "open" the function with a "{" and close it with "}" (without the quotation marks).
Everything between the { and the } is the contents of the function and will be run when the function is called.

We then create two links, which call the "myAlert" function.
To call a function, you must use the function name, and an open and closed parentheses.

Within the parentheses, you must match the number of variables the function "calls for". In this case, our function requires one variable (because we put one thing inside the parentheses when we created our function.

So, to call our function, we use: myAlert("something")

When Javascript reads this code, it will run the contents of our function, and replace msg with "something".

So, for our example, the first link will alert "test", and the second will alert "pizza".