Wednesday, July 17, 2013

Java Script - Basics

Introduction

Today’s websites need to go much beyond HTML. There is a definite need to allow users, browsing through a website to interact with the website. The website must be intelligent to accept user’s input and dynamically structure the contents of the webpage according to the input. This requires a website development environment that will allow the creation interactive of web pages.
Capturing user requests is traditionally done through a form. After a form captures user input, the form must have built-in technique for sending the information captured back to the web server for processing. The captured input need to be validated before sending it to the server. Hence the development environment must facilitate coding which runs in a browser at client side for data validation.
JavaScript allows us to add such capabilities to a webpage.
JavaScript is a scripting language introduced by Netscape. JavaScript made its first appearance in Netscape 2.0 in 1995 with a name LiveScript.
JavaScript is the world's most popular programming language. It is the language for HTML and the web. JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. JavaScript is programming code that can be inserted into HTML pages.

Advantages
Some of the other advantages of JavaScript are:
·        An Interpreted language: JavaScript is an interpreted language. So it does not require any compilation steps.
·        Quick Development: JavaScript does not require any special or separate editor. It also does not require time consuming compilation steps. This facilitates fast development.
·        Designed for simple small programs: It is well suited to implement simple, small programs (Eg: a unit conversion). Such programs can be written and executed at acceptable speeds.
·        Performance: JavaScript can be written in such a way that HTML pages are compact and small. As it is embedded in the HTML code, there is no need of additional network access to retrieve the page.
·        Procedural capabilities: JavaScript has capabilities of any programming language like condition checking, looping and branching.
·        Designed for programming user events: JavaScript supports event based programming. That is it can detect when an user event occurs (Eg: A button being pressed) and respond accordingly.
·        Easy Debugging and testing: Being an interpreted language, scripts in JavaScript are tested line by line and the errors are also listed as they are encountered. So its easy to locate errors.
·        Platform independence / Architecture neutral: JavaScript is completely independent of the hardware on which it works. Browsers are platform specific. They take care of implementing JavaScript according to the platform. This relieves the user of maintaining multiple source code files.

JavaScript Syntax
A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
You can place the <script> tag containing your JavaScript within the <head> or <body> of you web page, but it is preferred way to keep it within the <head> tags.
The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows
<script >
              JavaScript code
</script>
The script tag takes one important attribute language. This attribute specifies what scripting language is being used. Typically, its value will be javascript.
So your JavaScript segment will look like:
<script language="javascript">
                           JavaScript code
</script>

Data Types
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types:
·        Number: It defines all integer and floating point numbers and a special number NaN (Not a Number). Integers can be represented in Decimal, Octal and Hexadecimal format.
e.g. 123, 120.50 etc.
·        String: It defines all strings that are enclosed in single (‘ ’) or double (“ ”) quotes.
e.g. "This text string", ‘Krishna’ etc.
·        Boolean: Defines logical values true and false. JavaScript automatically converts true into 1 and false into 0 when used in numerical expressions.
·        Null: Defines only a single value null which identifies null, empty or non-existent reference.
JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format.

Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:
            <script language="javascript">
                                    var money;
                                    var name;
            </script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or later point in time when you need that variable as follows:
            <script language ="javascript">
                                    var name = "Ram";
                                    var money;
                                    money = 2000.50;
            </script>
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
Arrays
Arrays are JavaScript objects capable of holding a sequence of values. These values are stored in contiguous memory locations and accessed by the name of the array followed by the index. An array can be declared as below
            arrayName = new Array(length);
If an array is created without specifying the size, JavaScript creates an array of size zero and automatically extends the length of the array when elements are added.
            Eg: students = new Array();
Arrays are extendable even if the length is specified initially.
Dense Arrays
A dense array is an array that has been created with each of its element being assigned a specific value. They are declared and initialised at the same time.

Operators
JavaScript language supports following type of operators.
·        Arithmetic Operators
·        Assignment Operators
·        Comparison Operators
·        Logical Operators
·        The Conditional (or ternary) Operator
·        Bitwise Operators
·        Special Operators
Let us have a look on all operators one by one.

The Arithmetic Operators
There are following arithmetic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denominator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

The Assignment Operators
There are following assignment operators supported by JavaScript language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A

The Comparison Operators
There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
==
Checks if the values of two operands are equal or not, if yes then condition becomes true. Here the data type of the operands are not considered.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
===
Strictly equal. Checks the data type of the operands also.
10 == “10” is true
10 === “10” is false
!==
Strictly not equal. Considers the data type of the operands also.
20 != “20”  is false
20 !== “20” is true.

The Logical Operators
There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are non zero then the condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands are non zero then the condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.

The Conditional Operator (? :)

Conditional operator first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation.
The conditional operator has the syntax:
Operator
Description
Example
? :
If Condition is true ? Then value X : Otherwise value Y
k = (a==b) ? 10 : 2
k gets value 10 if a is equal to b and 2 if a is not equal to b

Bitwise Operators
There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
Operator
Description
Example
&
Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments.
(A & B) is 2
|
Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.
(A | B) is 3
^
Bitwise XOR operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
(A ^ B) is 1
~
Bitwise NOT operator. It is a unary operator and operates by reversing all bits in the operand.
(~B) is -4 .
<< 
Bitwise Shift Left operator. It moves the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.
(A << 1) is 4.
>> 
Bitwise Shift Right with Sign operator. It moves the bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder).
(A >> 1) is 1.
>>> 
Bitwise Shift Right with Zero operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero (not the sign bit).
(A >>> 1) is 1.

Special operators
JavaScript supports some additional operators other than those given above
Operator
Description
Example
new
The new operator is used to create an instance of an object type.
myArray = new Array();
delete
To delete a property of an object or an element at an array index
delete myArray[5]
deletes 6th element of the array

Placing Text in a Browser
JavaScript uses the write() method of document object for placing text in a browser. Methods are called combining the object name with method name.
objectName.methodName
The write() method accepts a string value as argument, and places it in the current browser window.

Example: document.write(“Hello World”);

Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
  • if statement - use this statement to execute some code only if a specified condition is true
  • if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement - use this statement to select one of many blocks of code to be executed
  • switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
      code to be executed if condition is true
}
Example
if (a<10)
{
      a++;
}
Here the variable a gets incremented if its value is less than 10.
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
Syntax
if (condition)
{
      code to be executed if condition is true
}else
{
      code to be executed if condition is not true
}
Example
if (a<10){
      a++;
}else{
      b++;
}
Here the variable a gets incremented if its value is less than 10 and b gets incremented if the condition is false
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(n)
{
      case 1:
                   execute code block 1
                   break;
      case 2:
                   execute code block 2
                   break;
      default:
                   code to be executed if n is different from 1 and 2
}
We have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Use the default keyword to specify what to do if there is no match:
Example
switch (day)
{
      case 0:
                   x="Today it's Sunday";
                   break;
      case 1:
                   x="Today it's Monday";
                   break;
      case 2:
                   x="Today it's Tuesday";
                   break;
      case 3:
                 x="Today it's Wednesday";
                 break;
      case 4:
                 x="Today it's Thursday";
                 break;
      case 5:
                 x="Today it's Friday";
                 break;
      case 6:
                 x="Today it's Saturday";
                 break;
      default:
                 x = "Invalid";
}
In the above example suppose day has a value 4, then x gets value ="Today it's Thursday". Suppose day is not in the range 0 to 6, then the default block is executed and x gets the value “Invalid”.

Loops
Loops can execute a block of code a number of times.
JavaScript supports different kinds of loops:
  •          for - loops through a block of code a number of times
  •          for/in - loops through the properties of an object
  •          while - loops through a block of code while a specified condition is true
  •          do/while - also loops through a block of code while a specified condition is true

The For Loop
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
{
       the code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Example:
for (var i=0; i<5; i++)
{
      document.write("The number is " + i + "<br>");
}

The For/In Loop
The JavaScript for/in statement loops through the properties of an object:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
       txt=txt + person[x];
}

The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition)
{
      code block to be executed
}
Example:
while (i<5){
      document.write("The number is " + i + "<br>");
       i++;
}

The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, and then it will repeat the loop as long as the condition is true.
Syntax
do
{
      code block to be executed
}while (condition);
Example:
do
{
      document.write(The number is " + i + "<br>");
      i++;
}while (i<5);

No comments:

Post a Comment