Wednesday, 2 October 2013

javascript programming basics

Programming Basics

As we know that javascript is a popular scripting language and it support variables. Programmers use variables to store values. A variable can hold several types of data. In JavaScript you don't have to declare a variable's data type before using it.

Javascript is not a strongly typed language which means you rarely have to concern yourself with
the type of data a variable is storing, only what the variable is storing and in Javascript, variables
can store anything, even functions.

 Any variable can hold any JavaScript data type, including:
  • String data
  • Numbers
  • Boolean values (T/F)

Variable Names

There are rules and conventions in naming variables in any programming language. It is good practice to use descriptive names for variables. The following are the JavaScript rules:
  • The variable name must start with a letter or an underscore. example:firstName or _myName
  • You can use numbers in a variable name, but not as the first character.Ex:name01 or tuition$
  • You can't use space to separate characters.Ex:userName not user Name
  • Capitalize the first letter of every word except the first. Ex. salesTax or userFirstName

 

Variables

 

  • To declare variables, use the keyword var and the variable name: Example:var userName 7 ;
  • To assign values to variables, add an equal sign and the value:Ex: var userName = "Smith"; var price = 100

 

Operators

 

Like other programming language javascript also support following Operators
  • Assignment Operators(=,+=,-=,*=,/=,%=)
  • Arithmetic Operators(+,-,*,/,%,++,--)
  • Comparison Operators(==,!=,<,<=,>,>=)
  • Logical Operators(&&,||,!)
  • Conditional Operator(variablename=(condition)?value1:value2)

Note:The + Operator Used on Strings example : 

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
 
//output:What a very nice day


Statements

  • Conditional statement (if, if.. else, switch)
  • Loop ( for loop, while loop )
  • try...catch throw

Conditional Statements

 

Want perform different actions for different decisions. You can use conditional statements in your code to do this. 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

example of If...else if...else Statement

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

example of switch Statement
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>


loops

 

Some time we need same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this
In JavaScript, there are three different kind of loops:
  • for
  • while
  • do ..while

Exampel for loop:
 
The for loop is used when you know in advance how many times the script should run.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Exampel while loop:
 
Loops execute a block of code a specified number of times, or while a specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>

Exampel do...while Loop
 
The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>

JavaScript Break and Continue Statements  

 


The break Statement
 
The break statement will break the loop and continue executing the code that follows after the loop (if any).

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>


The continue Statement
 
The continue statement will break the current loop and continue with the next value.

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement
 
The for...in statement loops through the elements of an array or through the properties of an object.
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.


<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
output:


JavaScript Try...Catch Statement


 
The try...catch statement allows you to test a block of code for errors.

Catching Errors
 
When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

The try...catch Statement
 

The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.



<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
output:

The Throw Statement

 
The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Example
 
The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(er)
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>


Functions

 

With functions, you can give a name to a whole block of code, allowing you to reference it from anywhere in your program. JavaScript has built-in functions for several predefined operations. Here are three some functions.
  • alert("message")
  • confirm("message")
  • prompt("message")

Function Example
 
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
output:

User-Defined Functions
 
With user-defined functions, you can name a block of code and call it when you need it. You define a function in the HEAD section of a web page. It is defined with the function keyword, followed by the function name and any arguments.

function functionName(argument)
{
statements
 }
 Example:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>


Output:


The return Statement
 
The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. The example below returns the product of two numbers (a and b):

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
output:


The Scope of JavaScript Variables (Life time of variable)

If you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables. You
can have local variables with the same name in different functions, because each is recognized only
by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime
of these variables starts when they are declared, and ends when the page is closed.

Explore more about java script events here.

No comments:

Post a Comment