Basic Concepts Of java script
The basic concepts of JavaScript are the following:
Case Sensitive
In Java script everything
is case-sensitive. Variables, function names, operators, and everything
else is case-sensitive, meaning that a variable named test is different
from one named Test.
Variables: -
Variables
are loosely typed. Variables are not given a specific type. Instead, each
variable is defined using the var operator and can be initialized with any value. This
enables user to change the type of data at any point of time.
Some examples:
var color = “red”;
var num = 25;
var visible = true;
Statements: -
Statements are terminated by a semicolon, though omitting the semicolon
makes the Parser determine where the end of a statement occurs.
var test1 = “red”
var test2 = “blue”;
Multiple Statements: -
Code blocks are used to indicate a
series of statements that should be executed in sequence and are indicated by
enclosing the statements between an opening brace ({) and a
closing brace (}).
For example:
if (test1 == “red”) {
test1 = “blue”;
alert(test1);
}
Comments: -
There are two types of comments:
single-line and multiline. The single-line comments begin with two
forward-slashes (//), whereas multiline comments begin with a forward-slash
and asterisk (/*) and end with an asterisk followed by a forward-slash
(*/).
//this is a single-line comment
/* this is a multiline
comment */
Keywords
Keywords are reserved and cannot be used as variable or
function names. Here is the complete list of JavaScript keywords:
break
else new var
case f inally return void
catch
for switch while
continue
function this with
default if throw
delete in try
do instanceof
typeof
Data Type
There are five simple data types
Integer
Represent 32 bit .Integers can also be represented as either
octal (base 8) or hexadecimal (base 16)
literals. For an octal literal, the first digit must be a zero (0), and the
following digits can be any octal digit
(0 through 7), as in this line of code:
var iNum = 070; //070 is equal to 56 in decimal
String
A string can be used to store
zero or more Unicode characters, represented by 16-bit integers. String
literals are specified by using either double quotes (“) or single quotes (‘). Boolean The Boolean type is one of
the most frequently used in the language. It has two values, true and false (which
are also the two Boolean literals). Even though false isn’t equal to 0, 0 is
converted to false when necessary, making it safe to use either in a Boolean
statement.
var
bFound = true;
var bLost = false;
Float
It include a decimal point and one digit after the decimal
point
(for
instance, use 1.0 not 1.). This is considered a floating-point number literal.
Example:
var fNum = 5.0;
For
very large or very small numbers, floating-point values can be represented
using e-notation. In e-notation, a number is represented by digits
(including decimal digits), followed by an e (or an E), followed by the number
of times to multiply it by 10. Confused? Here’s an example:
var fNum = 3.125e7
Null
The Null type, has only the special value null, which is also
its literal. The value undefined is actually a derivative of the value null
Operator.
Math
Operator
|
Meaning
|
+
|
Addition
|
-
|
Subtraction
|
*
|
Multiplication
|
/
|
Division
|
%
|
Modulus
|
++
|
Increment
|
––
|
Decrement
|
-
|
Negation
|
Strings are concatenated
together using the "+" operator.
Bitwise Operators
These operators work at the bit
level performing the operator function on a bit per bit basis. The operation
must be thought of as binary, octal, or hexadecimal values (depending on
preference) to consider how it works. Consider the decimal number 15.
15 & 3 = 3 - Equivalent binary: 1111 & 0011 = 0011
15 | 3 = 15 - Equivalent binary: 1111 | 0011 = 1111
15 | 16 = 31 - Equivalent binary: 1111 | 10000 = 11111
15 | 30 = 31 - Equivalent binary: 1111 | 11110 = 11111
Operator
|
Meaning
|
&
|
AND
|
~
|
NOT
|
|
|
OR
|
^
|
exclusive OR
|
<<
|
Left shift
|
>>
|
Right shift
|
>>>
|
Right shift, fill with zeros
|
Logical Operators
Logical operators operate on
boolean values which are either true or false.
Operator
|
Meaning
|
&&
|
AND
|
||
|
OR
|
!
|
NOT
|
Conditional Operator
The syntax for
the conditional operator is:
condition ? ActionIfTrue :
ActionIfFalse
Other Operator
Operator
|
Meaning
|
=
|
Assignment
|
,
|
Comma
|
.
|
dot
|
Data Type Conversion Functions
- isNaN() - If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false.
if (isNaN(string1))
{
document.write("String1 is not a number\n");
}
else
{
document.write(String1 is a number\n");
}
- eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string. Example:
value1
= eval("124/2") ,
becomes 62.
- parseInt()- Converts a string to an integer returning the first integer encountered which is contained in the string. In the example, value1 becomes 12.
value1
= parseInt("12b13") ,
If no integer value were
found such as in the string "abcd", then a value of 0 is returned.
- parseFloat() - Returns floating point numbers the same as the parseInt function, but looks for floating point qualified strings and returns their vlaue as a float. Everybody likes a good float in a parade of numbers. The first line below returns a value of 123, and the second line returns 9.683.
value1 = parseFloat("123")
value2 = parseFloat("9.683")
- toString() - Converts an object to a string. The syntax is shown below. Radix is the base value for the conversion, which may be 10 for decimal conversion. The value 1 is used for binary conversion, and 8 is used for octal conversion.
object.tostring(radix)
- typeof - This function returns the type of the object it operates on. Values returned are string values and may be one of "undefined", "object", "function", "number", "Boolean", or "string". The example will return the string "number".
typeof 10
- valueOf()
Statement
if
if (value == 3)
{
document.write("Value is three")
}
else
{
document.write("Value is not three")
}
While
The while
statement is a pretest loop. This means the evaluation of the
escape condition is done before the code inside the loop has been executed.
Because of this, it is possible that the body of the loop is never executed.
Syntax:
while(expression)
{
Statement;
}
Example :
var i = 0;
while (i < 10) {
i += 2;
}
Do While
The do-while
statement is a post-test loop, meaning that the evaluation of
the escape condition is only done after the code inside the loop has been
executed. This means that the body of the loop is always executed at least once
before the expression is evaluated.
Syntax:
do {
statement
} while (expression);
The example prints the days of
the week.
days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = 0
do
{
document.write(days[day] + " is day " + eval(day+1) + " of the week.<BR>\n")
day++
} while (day < 7);
For
The for
statement is also a pretest loop with the added capabilities of
variable initialization before entering the loop and defining post loop code to
be entered.
Syntax:
for (initialization; expression; post-loop-expression) statement
For example:
for (var i=0; i < iCount; i++){
alert(i);
}
This code defines a variable i that begins with the value 0. The for
loop is entered only if the conditional expression (i < iCount) evaluates
to true, making it
possible that the body of the code might not be executed. If the body is
executed, the postloop expression is also executed, iterating the variable i.
The following example will
determine what numeric day of the week Wednesday falls on.
ds = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var day = "Wednesday"
var place;
for (i = 0;i < ds.length;i++)
{
if (day == ds[i])
{
place = i + 1;
}
}
document.write(day + " is day " + place + " in the week.<BR>\n");
The switch statement
The switch
statement, allows a developer to provide a series of cases for an expression.
The syntax for the switch statement is:
switch (expression) {
case value: statement
break;
case value: statement
break;
case value: statement
break;
...
case value: statement
break;
default: statement
}
Each case says “if expression is equal to value, execute statement”. The break
keyword causes code execution to jump out of the switch
statement. Without the break keyword,
code execution falls through the original case into the following one.
The default
keyword indicates what is to be done if the expression does not
evaluate to one of the cases (in effect, it is an else
statement).
Runs one or more commands based
on the value of the expression being evaluated. An example is:
switch (day) {
case 1:
document.write("Sunday<BR>\n")
break
case 2:
document.write("Monday<BR>\n")
break
case 3:
document.write("Tuesday<BR>\n")
break
case 4:
document.write("Wednesday<BR>\n")
break
case 5:
document.write("Thursday<BR>\n")
break
case 6:
document.write("Friday<BR>\n")
break
case 7:
document.write("Saturday<BR>\n")
break
default:
document.write("Invalid Weekday<BR>\n")
break
}
Break
The break statement may be used
to break out of a while, if, switch, dowhile, or for statement. The break
causes program control to fall to the statement following the iterative
statement. The break statement now supports a label which allows the
specification of a location for the program control to jump to. The following
code will print "Wednesday is day 4 in the week".
days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i]) break;
}
place = i + 1
document.write(day + " is day " + place + " in the week.<BR>\n")
Continue
The continue statement does not
terminate the loop statement, but allows statements below the continue
statement to be skipped, while the control remains with the looping statement.
The loop is not exited. The example below does not include any ratings values
below 5.
ratings = new Array(6,9,8,4,5,7,8,10)
var sum = 0;
var reviews = 0
for (i=0; i < ratings.length; i++)
{
if (ratings[i] < 5) continue
sum += ratings[i];
reviews++;
}
var average = sum/reviews
For in Statement
Executes a loop similar to a for
statement that executes for all the properties in an object. The example below
lists all properties and their values for the document object. The document is
the HTML page being displayed.
for (i in document)
{
document.write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
A few of the properties and
their values are:
Property = activeElement Value = [object]
Property = alinkColor Value = #ff0000
Property = all Value = [object]
Property = anchors Value = [object]
Property = applets Value = [object]
Property = bgColor Value = #ffffff
Property = body Value = [object]
Property = cookie Value = pageCount=9
Property = defaultCharset Value = iso-8859-1
Property = domain Value =
Property = embeds Value = [object]
Property = fgColor Value = #000000
Property = fileCreatedDate Value = Thursday, September 21, 2000
.
.
With Statement
The with statement
is used to set the scope of the code within a particular object. Its syntax is
the
following:
with (expression) statement;
For example:
var sMessage = “hello world”;
with(sMessage) {
alert(toUpperCase()); //outputs “HELLO
WORLD”
}
In this code, the with
statement is used with a string, so when the toUpperCase()
method is called, the interpreter checks to see if this is a
local function. If not, it checks the sMessage pseudo-object
to see if toUpperCase()
is a method for it, which it is. The alert then outputs “HELLO WORLD” because the
interpreter finds the implementation of toUpperCase()
on the “hello
world” string
Eliminates references to the
object within the statement by identifying the default object to be used inside
the braces. This example prints out the document properties and values without
referencing the document object to perform the function.
with (document)
{
for (i in this)
{
write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
}
JavaScript Functions
Defining Functions
Javascript functions are defined
using the key word "function" followed by its name and variables
being passed to it in the following syntax:
function fname(value1,value2, ...)
{
statement1
statement2
.
}
An example:
<HTML>
<HEAD>
<TITLE>A function definition</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hiding JavaScript
function listItems(itemList)
{
document.write("<UL>\n")
for (i = 0;i < itemList.length;i++)
{
document.write("<LI>" + itemList[i] + "\n")
}
document.write("</UL>\n")
}
// End hiding JavaScript -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
days=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
listItems(days)
// -->
</SCRIPT>
</BODY> </HTML>
Calling Functions
If evaluate() is a defined
function, the following line will call the function:
<SCRIPT LANGUAGE="JavaScript">
<!--
i3 = evaluate (Tree)
// -->
</SCRIPT>
This function may evaluate the
members of the array tree to see how many match a certain criteria.
Another way to call a function
is to tie it to an anchor:
<A HREF="javascript:redirectLink()">redirecting</A>
Another way is to tie it to an
event:
<A NAME="javatest" onClick="redirectLink()">redirecting</A>
This will cause the
redirectLink() function to run when the text "redirecting" is clicked
on. The text inside the anchor reference is not marked as a link, nor does the
mouse change when placed over the text. This is one way to make truly invisible
links, that no one would know had any function until they click on it.
Functions Properties
Functions in JavaScript is
actually an object. Therefore any created function created using the
"function" declaration will have the properties of a function. These
properties are:
- arguments - An array of arguments passed to the function. This is an array object which has a property of length which enables the programmer to tell how many arguments (or variables)are passed to the function.
- caller - The name of the function that called the function.
- prototype - Used to make more properties.
Using the Arguments Array
The arguments array is a member
of every function. It can be used to determine how many variables are being
passed to the function, and what they are, without each argument being
explicitly declared in the function. The following example performs the same
task as the above example:
function listItems()
{
var items = listItems.arguments.length
document.write("<UL>\n")
for (i = 0;i < items;i++)
{
document.write("<LI>" + listItems.arguments[i] + "\n")
}
document.write("</UL>\n")
}
The function may be called as
follows:
listItems("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Happyday")
Global Variables
Global variables may be defined outside functions.
Local variables
Local variables may be defined
inside functions. The following example uses the variables, sum and items as
local variables.
function average()
{
var items = average.arguments.length
var sum = 0
for (i = 0; i < items;i++)
{
sum += average.arguments[i]
}
return (sum/items)
}
document.write(average(6,9,8,4,5,7,8,10))
Return
The return statement will return
a value to the statement that invoked the function. In the above example, the
average value is written to the document. The return statement will return the
value as float, string, integer or whatever is appropriate for use.
No comments:
Post a Comment