Hosting Solutions  
 
   |  Tutorials Home  |  Privacy | 









Secured by RapidSSL



7 ~ Operators, Strings and Values

(1)    (2)    (3)    (4)    (5)    (6)    (7)    (8)   

There are four basic types of data in JavaScript:

Strings, like "It's a fine morning!". Strings are composed of text or numbers, and surrounded by quotes.

Numbers, integers like 6 or 7, and floating-point like 3.1417 or 59.95.

Boolean values, sometimes called logical values. Boolean can return only two values, either 'true' or 'false'.

null, which is the value of an undefined variable. For instance 'document.write(whatever)' will show a value of 'null' if the variable 'whatever' has not been defined.

Strings are fairly simple to understand and you should have a little familiarity with them by now. To refresh things a bit, here are a couple of examples:


var myName = "Bill"
var addr = "123 Elm Street"

You may have occasion to test for the length of a string, and it is done like this:

var address = "123 Elm Street";
document.write(address+" has "+address.length+ " characters");

The output:

Comparing Values using Conditional Statements

The ability to compare values is one of the most important features of a programming language. Testing for and comparing values will allow you to branch to different scripts or otherwise modify the behavior of your document based on user input. Conditional statements have two parts:

If  Condition,  then  Action

The code will test for the condition, and based on the value of the condition, will then take a certain action. To put it in plain terms, "If the light is green" (the condition), "then go ahead" (the action). Here's a typical conditional statement:

If (Answer == "Y") window.alert("You entered Yes");

The condition in this statement is that if 'Answer is equal to 'Y', (the condition is met), then the message is displayed. The double equal symbol (==) is one of many conditional operators, of which there are some examples further on in this lesson. This particular operator is also an equality operator. It's counterpart, the single 'equal' symbol (=) is an assignment operator.

If you have an instance where you need multiple statements if your script, you can do so by enclosing them in braces like this:

If (Answer == "Y")
{
window.alert("You entered Yes");
}
else
{
window.alert("You did not enter Yes");
}

The difference between the two 'equal' operators is that the first type, '==' , is used to test if values are equal to each other, while the single '=' is used to assign a value to a variable, a constant or an expression. This is an area of "javascript" programming that confuses many people, and is therefore important to remember.

Here are some of the more common assignment operators:

=
==
+=
- =
++
- -
/
*
>
<
<=
>=
<>
!=
^
'equals'- Assigns a value ex: num=5
equal to- Compares two values ex: if(num==5)
increments the value of a variable. ex: num+=1 or 'num=num+1'
decrements the value of a variable. ex: num-=1 or 'num=num-1'
increments one to the value. ex: num++
decrements one from the value. ex: num--
division. ex: num/2=2.5
multiplier. ex: 3*3=9
greater than. ex: 10>5 would give the boolean value as true
less than. ex: if(5<10)
less than or equal to.
greater than or equal to.
greater or lesser than; or equal to anything but.
not equal to.
bitwise XOR by value.

...and some other operators:

&
&&
|
!
bitwise And.
logical And.
logical Or. (Or if)
logical Not.

Sometimes you may need to check more than one variable for a value at the same time, like this:

if (answer=" ")window.alert ("No name was entered!");
if (address=" ")window.alert ("No URL was entered!");

We can use a logical operator to make it a single statement:

if (answer=" " || address=" ") window.alert ("No name or URL!");

The above uses the logical operator OR (||) to combine the conditions; the script is saying, in effect: "If the name value is empty OR the address value is empty then print the message."

And this statement, using the logical operator 'AND' (&&)...

if (answer=" " && address=" ") window.alert ("No name or URL!");

... says in effect: "If the name value is empty AND the address value is empty then print the message."

Another logical operator often used is NOT, and this is signified by the exclamation mark (!).

if (gender != "female") window.alert ("Sex is Male");

This operator as used with '=' operator above means simply "Not equal to".

Math

When more than one operation occurs in a math expression each part is resolved and carried out in a predetermined order; this order is known as Operator Precedence. If this precedence needs to be altered, parentheses can be applied around the specific operation. Operations indide of parentheses are always done before those outside the parentheses; however, the normal order of precedence is applied inside the parentheses.

If an expression has operators from more than one category, the arithmetic operators are evaluated first, comparison operators secondly and logical operators last. Here are some charts of operator precedence:

Order Arithmetical Ops
1st
2nd
3rd
4th
5th
6th
Exponentiation  ^
Negation  -
Multiplication  * and division  /
Integer division  \
Addition  + and Subtraction  -
Order Conditional Ops
1st
2nd
3rd
4th
5th
6th
Equality  =
Inequality  <>
Less than  <
Greater than  >
Less than or equal to  < =
Greater than or equal to  > =
Sitebilder Free Website Tutorials
Order Logical Ops
1st
2nd
3rd
4th
5th
6th
Not  !
And  &&
Or  ||
 

Here's a little example of why operator precedence can be important to you; suppose you want to subtract 2 from 4 and multiply the result by 6 like this:

var x=4-2*6
document.write("4 - 2 * 6 = " + x)

Here's the result:

That's not quite what you expected, is it? The order of precedence caused 2 to be multiplied by 6 first, then the product was subtracted from 4, which gives us a negative 8. Algebraic expressions don't work normally in "javascript". In order to get the answer we want, and keeping the precedence of operations in mind, we have to do it this way:

var x=(4-2)*6
document.write("(4 - 2) * 6 = " + x)

And we get what we expected:

Even Einstein would have to comform to "javascript"'s operator precedence and change his e = mc2 to this format: e = (mc)^2.

Before we wind this chapter up, there is one more thing that should be mentioned, and that's the Math object. The Math object is a function which is built-in to "javascript". You don't have to create this object as it is in existence automatically in any "javascript" program. The properties of the Math object represent math constants, and math functions are its methods. Let's start with some of the methods.

The Math.random() method returns a random decimal number between 0 and 1. To change this to an integer, we can use the Math.floor method. Here's a simple random number function using both of these methods:

<script language="Javascript">
<!--hide
function randm()
{
num = Math.floor(Math.random()*9);
if (num==0)
alert("the number is "+num)
if (num==1)
alert("the number is "+num)
if (num==2)
alert("the number is "+num)
if (num==3)
alert("the number is "+num)
if (num==4)
alert("the number is "+num)
if (num==5)
alert("the number is "+num)
if (num==6)
alert("the number is "+num)
if (num==7)
alert("the number is "+num)
if (num==8)
alert("the number is "+num)
}
//-->
</script>

Go ahead and punch the button a few times to see it work.

JavaScript is a little limited as far as generating truly random numbers goes, but it is sufficient for most web uses. This script could be modified to either print out quotations or to load a random picture with little effort. Here's a brief rundown on how it works.

First, Math.floor changes the random number generated by Math.random to a decimal value between 0 and one (Math.random gets its number from reading your system timer which operates in milliseconds). The result is multiplied by a whole number to give us an integer. In this case, I wanted a number between 0 and 8 so I used the number 9 as the multiplier. Don't forget that "javascript" counts from 0 and considers zero a literal value. If this is confusing to you, you can modify the above like this, and you will only have to work with whole numbers:

num = Math.floor(Math.random()*8) + 1;

Keep in mind however, that if you use this this modification, the random numbers you will get will start from one instead of zero, and you will have to change the if (num==0) to read if (num==1) and so on to the end of the script, the final comparator being if (num==9). Got it? Good.

The rest of the script is pretty self-explanatory. Of course, the function belongs between your Head tags. Here's the code for the button I used to call the function:

<form>
<input type="button" value="Random"
onClick="randm()">
</form>

If you wanted to use the function to load random quotes or images when your page loads, the call should be place in the Body tag like so:

<body onLoad="randm()">

That's about it for now; see Ya in the next lesson!

[Printer Friendly Page]


Lesson 8

(1)    (2)    (3)    (4)    (5)    (6)    (7)    (8)   





Updated on Thursday, 01~26~2012

Copyright © 1998 - 2012
Bill Payne & Sitebilder© Network