Monday, January 6, 2014

Introduction to JavaScript Series Part-3

Before going through this blog please check Part-2.

Control Structure in JavaScript

if else  

It is used to evaluate condition and execute statements based in evaluation.

if(condition){
//statements
}else if(condition){
//statements
}else{
//statements
}

Turnery operator

Turnery operator is same as if else statement. It evaluates the expression and executes one of the statements.

var result = (condition)? Statements: Alternatives;

var result = (true)? alert(‘True’): alert(‘False’);
Here both statements and alternatives should be specified. Above code will show True in alert.

Switch Statement
Switch Statement is used to evaluate condition and execute more than one cases based on it.

switch(condition){
case firstvalue: break;
case secondvalue: break;
case thirdvalue: break;
default: break;
}

break statement is optional but it's necessary to stop execution of next cases. default is optional, but generally it is use to manage default case. String literals can be used instead of values.

For Loop

For loop is used to execute statements more than till particular condition is matched.

for(initialization; condition ; increment) {
//statements
}

For In loop

Generally for in loop is used to iterate through all the properties of object or all the indices of an array.

for( var property in object){
//statements
}

While loop

While loop is used to execute statements more than once based on certain condition. Unlike for loop there is no increment in while loop.

while(condition){
//statements
}

Do While loop

Do while loop is same as while loop. Only difference is, statements inside loop will be executed at least once.
do{
//statements
}while(condition)

How to use JavaScript

JavaScript can be inserted in any html page with Script tag in head section

<head>
<script type=”text/javascript” language=”JavaScript”>
//JavaScript statements.
</script>
</head>

Also JavaScript can be placed in external file with .js extension and can be referenced in head section.
<head>
<script src=”myfile.js” language=”JavaScript” />
</head>
Also JavaScript can be placed in external file with .js extension and can be referenced in head section.

No comments:

Post a Comment