TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

JavaScript Programming

Broadly speaking, two things are of primary importance in any kind of problem solving, be it life or programming. First, the ability to assess a given problem and formulate a working solution in one's head or on paper within the given framework of tools. And second, the knowledge of using the tools themselves and implementing the solution using them. If we fit this analogy to programming the first step improves with experience and the second is learnt through books, online tutorials or other such means.

JavaScript Tutorial Part II - The LanguageIt is not as if things don't work the other way, they do, but in general more experience leads to a better appreciation of a given problem and a clearer understanding of the various possible pitfalls in any one of the many possible solutions. Books and Tutorials can give an idea or show a particular method for arriving at the solution for a given problem, but they can't cover what is learnt through endless hours of coding. So, get your hands wet and start with Javascript.

This part will provide a basic introduction to the Javascript language, Part 3 Common Scripts will discuss solutions to some common tasks faced by the javascripter. Even if you find Part 2 a little dry and boring it is important that you go through it and understand some of the basics of Javascript. Later, in Part 3 we will put them all to use.

Inserting Javascript into HTML

<html>
<head> </head> 
<body>
<script language="Javascript"> 
document.write("My first javascript!")
</script>
</body>
</html>

All lines encountered by the browser after the <script> tag are treated as client-side code. This code is then executed by the browser instead of being displayed as HTML content. All lines following the </script> tag are again processed as HTML. The language attribute specifies that language, this can either be VBScript or Javascript.

Where to put Javascript

Within an HTML document the <script> tag can be placed any number of times, it is like any other tag, and like most tags <script> has to be ended with </script>. As soon as the Javascript code is loaded into the browser it is executed, sometimes we may not want that. In cases like that when the script is executed when called (most often functions) we place it in the head section.

<html>
<head> 
<script language="Javascript"> 
......Javascript Statements.......
</script>
</head> 
<body>
</body>
</html>

We can also have Javascript in the head and the body section.

<html>
<head> 
<script language="Javascript"> 
......Javascript Statements.......
</script>
</head> 
<body>
<script language="Javascript"> 
......Javascript Statements.......
</script>
</body>
</html>

There are many occasions when a particular script is used on multiple pages. For situations like these an external script can be written and saved in a ".js" file. This can be then be called using the "src" attribute.

<html>
<head> </head> 
<body>
<script src="filename.js"> </script>
</body>
</html>

It is to be noted that the external Js file cannot contain the <script> tag.

Who said "old is gold" ?

Older browsers that are not script-aware will just ignore the script tag and display the Javascript within the HTML instead of executing the code, this can be a serious problem. So there is a way around it, we simply put our Javascript within an HTML comment block.

<script language="JavaScript">
<!-- 
......Javascript Statements....... 
//-->
</script> 

This way older browsers will ignore the Javascript code. This should not be confused with Javascript comments which uses the symbol "//" for single line comments and "/*" - "*/" for a comment block. The following example should make things clear.

<html>
<head> </head>
<body>
<script language="Javascript">
<!--
document.write("My second javascript that demonstrates single-line and multi-line comments")
document.write("<br>")
// this is a javascript comment, everything in this line will be treated as a comment document.write("Now, let us look at a multi-line comment")
/* everything inside this will be treated as a comment. Haha, Javascript you can only see me, but can't do a thing about me */
//-->
</script>
</body>
</html>

Variables

A variable is an area in the memory set aside to store certain data, or you can call it a "container" that stores your data. In a matter of speaking you can put data into the container, retrieve data from it or change the contents of this "container". You refer to the variable by its name (variable identifier). Remember that in Javascript variable names are case sensitive thus "age" is not the same as "AGE" or "Age". All variable names must begin with letter or the underscore character.

In Javascript variables can be declared in one of two ways.

var temp = value temp = value

Similarly variables can be assigned values in one of two ways.

var scientist = "Albert Einstein" scientist = "Albert Einstein"

The assignment operator "=" is used to assign values to variables as we just saw. In this case the variable identifier "scientist" is assigned the value "Albert Einstein". It has to be pointed out that Javascript is untyped language, this means that a Javascript variable can contain any data type. In the example below the variable number holds the integer value 2 when it is declared, then it is assigned the string value "small number".

var number = 2 number = "small number"

Operators (courtesy w3schools.com)

Arithmetic operators

Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x=4
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus. Returns the remainder after the first division

5/2 results in 2, remainder 1
10/8 results in 1, remainder 2
9/2 results in 4, remainder 1

5%2
10%8
1
2
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4

Assignment operators

Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y

Comparison Operators

Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

String Operator

A string is most often a text, for example "Hello World!". To stick two or more string variables together, use the + operator.

txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2 

The variable txt3 now contains "What a very nice day!".

To add a space between two string variables, insert a space into the expression, OR in one of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
or
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

Control Structures

Any kind of programming requires a basic understanding of control structures. Like most of the other languages Javascript offers conditional statements and looping statements. In addition to the 3 basic conditional statements Javascript provides a conditional operator. Let us look at these.

if

An if statement is used when a certain script is to be executed when a particular condition is met. The syntax is as follows

if (a certain condition is true) 
{
   // do something
}

if..else

Sometimes we may want to take certain actions if a particular condition is true and take different actions in case it is false. For this we use

if (a certain condition is true) 
{
   // do something
}
else
{
  // do something else
}

switch

Often we need to check for multiple possibilities for a given condition, the switch statement comes in handy in situations like these.

switch (expression)
{
case value1:
  // do something if expression = value1
  break    
case value2:
  // do something if expression = value2
  break
case value3:
  // do something if expression = value3
  break
default:
  // do something if the expressions is not value1,
  //                                        value2 or value3 }

It should be noted that after a particular case is executed by the switch statement, by default it moves on and executes all the cases after that one. To avoid this we put a break in every case.

<html>
<head></head>
<body>
<script language="Javascript">
<!--
var color = "red";
switch (color)
{
case "white" :
document.write("ethereal white");
break;
case "blue" :
document.write("sublime blue");
break;
case "red" :
document.write("bright red");
break;
case "green" :
document.write("environmental green");
break;
default :
document.write("you expect me to cover every conceivable color !!! wierdo");
}
//-->
</script>

</body>
</html>

Try giving different values to the variable color and see what happens. You will see that in the previous example a ";" has been placed after every statement. Javascript allows both ways - you may wither put a ";" after every statement or omit it out. Some people say it is a good practice to put the semi-colons.

Conditional Operator

In addition to these 3 conditional statements Javascript provides a conditional operator that assigns a value to a variable depending on a certain condition.

variablename = (condition)?value1:value2 
example :
child = (sex == "male")?"son":"daughter"

while

while (a certain condition is true) 
{
   // do something
}

The while loop evaluates an expression. If the condition evaluates to false, the statement inside the parentheses is skipped otherwise the code inside the braces is executed till the condition becomes false.

<html>
<head> </head> 
<body>
<script language="Javascript"> 
<!-- 
while (a certain condition is true) 
{
   // do something
}
//-->
</script>
</body>
</html>

do..while

In the case of a do..while loop the conditions is evaluated after the code block inside the braces is executed. In other words the code is executed at least once and then till the condition is true the block is executed.

do 
{ 
  // do something
} 
while (a certain condition is true) 

for

The for loop basically executes a code block a certain number of times.

for (initialization; condition; increment)
{
   // do something
}

Functions

Functions are pieces of reusable code that can be typed separately and called whenever necessary. Functions also help in organizing the code and making it more readable. Javascript functions are generally put in the head sections of an HTML document. This is how a function would look like in the head section.

<HEAD>
 
<SCRIPT language="JavaScript"> 
<!--hide from old browsers 
function name_of_function (argument1, argument2, argument3, ...)
{ 
 // code of the function comes here
} 
//--> 
</SCRIPT> 
</HEAD>      

An example of such a function would be.

<HEAD>
 
<SCRIPT language="JavaScript"> 
<!--
function print_good (name, gender)
{ 
 if (gender == "male")
 {
   document.write(name+" is a good boy");
 }
 else
 {
   document.write(name+" is a good girl");
 }
} 
//--> 
</SCRIPT> 
</HEAD>      

The above function would be called as follows.

print_good("Gary", "male");

Sometimes we want functions to return a value, in these cases we use the return statement, for example

<HEAD>
 
<SCRIPT language="JavaScript"> 
<!--
function complex_math (num1, num2, num3, num4)
{ 
 result = (num1+num2)/(num3+num4);
 return result;
} 
//--> 
</SCRIPT> 
</HEAD>      

And this sort of function is called like this.

answer = complex_math(4,8,2,1);

Well that is all for the moment. We shall look at many functions real life examples. Having read this you should have an idea of the Javascript language. Next week in Part 3 Common Scripts get ready to see Javascript in action.

Return to the top of the page.

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Dai's Comment
Great cmomon sense here. Wish I'd thought of that.
25 Wed Apr 2012
Admin's Reply:

Thanks Dai.




Raquel's Comment
I'm rlleay into it, thanks for this great stuff!
23 Mon Apr 2012
Admin's Reply:

Thanks for visiting Raquel.




Olya's Comment
You are so awesome for helping me solve this msytrey.
23 Mon Apr 2012
Admin's Reply:

You're Welcome




roopesh's Comment
really helpfull
12 Thu Nov 2009
Admin's Reply: Thanks Roop.





Facebook