You are on page 1of 22

What is JavaScript? JavaScript is scripting language used for client side scripting.

JavaScript developed by Netscape in 1995 as a method for validating forms and providing interactive content to web site. Microsoft and Netscape introduced JavaScript support in their browsers. Benefits of JavaScript Following are the benefits of JavaScript. • • • • • • associative arrays loosely typed variables regular expressions objects and classes highly evolved date, math, and string libraries W3C DOM support in the JavaScript

Disadvantages of JavaScript • • Developer depends on the browser support for the JavaScript There is no way to hide the JavaScript code in case of commercial application

Creating your first JavaScript Program In the first lesson we will create very simple JavaScript program and run in the Internet Explorer. This example simply displays "Welcome to JavaScript World!" message in the browser.

Here is the code of JavaScript program:

<html> <head> <title>First Java Script</title> <script language="JavaScript"> function sayhello(){ alert("Welcome to JavaScript World!"); } </script> </head> <body> <p><b>Click the following link to run your first java script example</b></p> <p><a href="javascript:sayhello()">Run JavaScript First Program</a></p> </body>

Example .JavaScript Statement The JavaScript language supported Two type Condition. The if statement is the most used features of JavaScript.Function if Statement The if statement is used to make decisions in JavaScript. 1. Boolean operators are also used in along with the if statement. There can be as many parameters separated by commas as you need. Example <HTML> <HEAD> </HEAD> <SCRIPT language="JavaScript"> <!-var num = 10 if(num == 10) { document. It is basically the same in JavaScript as it is in other programming languages.if statement 2. These parameters are variables which are used by the JavaScript statements inside the curly braces { }. The function can return a value by using the return keyword. The variable keyword is not needed to declare the parameters in a function as variables because they are automatically declared and initialized when the function is called.write("<B>Statement!</B><BR>") } //--></SCRIPT> my program successfully completed </BODY> </HTML> Function The function keyword identifies as a function. This is perfectly ok to have a function with no parameters. The parameters in the parenthesis ( ) provide a means of passing values to the function.

5). } var mul=prod(2.write("Good day!") } </script> </BODY> </HTML> . you want to execute some code if a condition is true and another code the condition is not true. </script> </BODY> </HTML> Conditional JavaScript if-else Statement The JavaScript Conditional Statement used to different actions and used to based on different conditions. use the if. document.getHours() if (time < 20) { document.write("Good morning!") } else { document.write("multipication:"+mul).<HTML> <HEAD> </HEAD> <script languane="JavaScript"> function prod(a..b) { var x=a*b return x..else statement.. Example <HTML> <HEAD> </HEAD> script type="text/javascript"> var a = new Date() var time = a.

then assigned a string value and later be assigned an object reference.A variable declared or initialized outside a function body has a global scope. has null value num = 20 // assign a value. A variable could be a number on one line. Local scope Variable. JavaScript would change its data type dynamically . the variable has a global scope and is only accessible after the function containing it is invoked. Variable Scope There are two types of Variable scope:1. These names are called variables.b. Globle scope Variable:. making it accessible to all other statements within the same document. 2 . 1.A data type is defined by the value assigned to it . 2. null value is replaced //OR var num=20 // declare AND assign value (initialize) var a.d=8 //multiple variables may be initialized simultaneously Variable Names Variable names cannot contain spaces. Declaring and Initializing the Variables var num // declare variable. The two words can either be separated by an underscore (my_variable) or (myVariable).It also represent the data's nature. When a value is referred in a statement. c = 7. It is safer to always use the var keyword ] Java script Data type Data Type:. [NOTE:. literal values can be named in order to make repeated reference to them practical. Data is directly treated on those data types and calculate up on the works . JavaScript Variable name can not use any reserved keywords. making it accessible only to statements within the same function body. b = 6. .d //multiple variables may be declared simultaneously var a = 5.c.Globle scope Variable:.Every piece of data is known as a value. it is called a literal value.JavaScript Variables .If a variable is initialized inside a function body but the var keyword is left off. For the same reason people are identified by names as opposed to "human" or "person". begin with a number and can not be used the underscore (_) .A variable declared or initialized within a function body has a local scope. efficient and readable. Globle scope Variable.

40.Primitive data types:. sum=a+b. Our statements are checked true or false then we use the Boolean variables. There are following types :• numeric:-JavaScript supports both integers and floating point numbers .Compositive data types 1. var sum=0.write(" sum= "+sum). document. As follow:1.50. document.If the string starts with a single quotes and it must end with single quotes . Floating point numbers are fractional numbers or decimal numbers .50 • string:.Primitive data types 2.There are two types of the data types.A variables to be declared but given no any initial value then it runtime error display Example for :-This example is represent the sum of two floating numbers and print the messages in single quotes and double quotes.write("\t\tHello\nworld!\n").Such as : 145 . Such as : 'Welcome to JavaScript' or "Welcome to JavaScript".String is a collection of characters enclosed in either single quotes and double quotes . • Boolean:-Boolean literals are logical values that have only one of two values. It used to conditional sanitations. Such as : 12.Integers are whole numbers and it does not support the decimal numbers . true or false.If the string starts with a double quotes and it must end with double quotes . document. } </script> .write('\nWelcome to JavaScript'). • • null:-The null value represents no value that means strings are empty . undefined:. <html> <head> <script language="javascript"> function showAlert() { var a=200.Primitive data types are the simplest building blocks of a program. var b=10.

</script> </body> </html> This program is used to Boolean expression and it display the numbers between 1 to 500 and if user to not enter the number then it display the you did not enter any number. else if(n>=30 && n<40) document. document.write("Your entered number is greater than 40 and less than 100"). else if(n>=20 && n<30) document. if (n>=1 && n<10) document.write("You did not enter any number!") .write("Your entered number is greater than 100 or less than 500").write("Your entered number is :"+n). else if(n>=100 && n<=500) document. else document.</head> <body> <script language="javascript"> showAlert(). <html> <body> <script type="text/javascript"> var n=0.write("Your entered number is greater than 20 and less than 30").write("Your entered number is greater than 1 and less than 10").write("Your entered number is greater than 30 and less than 40"). n=prompt("Enter a number"). else if(n>=40 && n<100) document. else if(n>=10 && n<20) document.write("Your entered number is greater than 10 and less than 20").

for example. The alternative method of convert a value into a string to pass it is argument to the String constructor called as a function. Exam:- Var string Value= String(d). when one of its operators not a number. The problem arises from dual nature of the + operator used for the both numeric addition and string concatenation. Because the value properties of form controls are strings if the even then character is sequence they contain represents a number of the attempt to add that string to a value. results in the second value being type-converted into a string and concatenated to the end of the first string value from the from control. The easy way of getting the string that results from type-conversion is to concatenate a value to string. There are any mathematical operation except the concatenation addition operator will force type-conversion. So the conversion of a string to a . JavaScript being is the loosely typed and willing to type-convert still does not save the programmer from need to the think about the actual type of values that they are dealing with.</script> </body> </html> What is String Number Operation? The JavaScript String is a loosely type language. Otherwise it converts all of its operands to strings and does concatenation. This is not mean that it has no data types that the value of a variable or a JavaScript object property does not need to have a particular type of the value assigned. or that it should be always hold the same type of value. A very common error in browser scripting. Converting String: The String most often from the action + Operators. it is to read the value property of a form control into which the user is expected to type a number and then add that value to another number. which the nature of the operation performed is determined by the context. even if the value happens to be a number. Converting Number: The Converting values to numbers especially to strings numbers. JavaScript also freely type-converts values into a type require by the context of their use. it is an extremely common requirement and many methods can be used. where only both the operation are numbers to start with the + operator perform addition.

write('my program'.lastIndexOf('T')). 10)).toUpperCase()).indexOf('T')). document. document.write(' program'. etc. var numValue = stringValue * 1.substring(1.charAt(10)). var numValue = stringValue / 1. document.write(' Test'.write('This '.write(' first JavaScript program'. document. document. This primer are going to take a step back and cover the inner workings of some of the native JavaScript objects: Strings. loops. var numValue = stringValue .write('This program Test'. document. document. such as subtracting zero or multiplying by one. Numbers and Arrays.number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number.write('This is test'.substr(7.length). Example: <html> <head> <Script language="JavaScript"> document. document.toLowerCase()).0.write('my exam Test'. String in JavaScript The JavaScript language until now we have been focusing on the language constructs of JavaScript: if statements. functions. 10)).write("<br />") </script> </table> </body> </html> .

'2nd'. Each item an array can be whatever you want. conversions.'santosh']. mul = 25 * 5. we will learn how to work with numbers in Java.Array in JavaScript Array is the basically just a list of items. //modulus division document. i++) { alert('The '+suffixes[i]+' student is '+students[i]). . var suffixes = ['1st'.5. document. //multiplication divided = 30 / 5. including arithmetic. modulus = 10 % 10.'5th']. '3rd'. 'susil'. '4th'. } </script> </head> </body> </html> JavaScript in Number Operation The numbers is a central task for the many programs. the desire to automate number operations was the motivation that drove the invention of digital computers decades ago. 'rani'.write("sum:"+sum). 'vinod'. but they are usually related to one-another. sub = 15 . Example: <html> <head> <Script language="JavaScript"> var sum = 10 + 10.write("sub:"+sub). Example: <html> <head> <script language="JavaScript"> var students = ['amar'. for(var i=0. and other numeric operations. In fact. i<=4.

This statement is used to when the condition is true then our code to execute and when the condition is false then our written code is not execute.else statement:. We can use conditional statements in our code. document.write("divided:"+divided). Syntax for the if . Syntax for the if statement:if ( expression ) { statement1 statement2 } • if . Conditional statements in JavaScript are used to perform different actions based on different conditions.else statement:if (expression) statement1 else if (expression2) statement2 else statement3 .It means the condition is true then our writing code is executed other wise our code is not execute .write("modulus:"+modulus). </script> </head> </body> </html> About Conditional Statement First of all we write the code after that we want to perform the different actions for different decisions. document. There are following types of Conditional Statements:• if statement:.document.write("mul:"+mul).

if(sum==3) { document.write("Condition is false"). <html> <head> <script language="javascript"> function showAlert() { var a=20. switch statement:-This statement is used to if you want to select one of many blocks of code to be executed. document.write(" This is my first if -else statement program"). document. sum=a+b. document.else statement -This statement is used to if you want to select one of many blocks of code to be executed . Syntax for the switch statement:switch (expression) { case1: statement1 break case2: statement2 break default: statement3.write(" sum= "+sum)... It display the first of all the sum of two numbers and check the condition after that it execute the code.write("This is my first if statement program"). } } .. } This example is if .• • if. var b=10.write("Condition is true").else statement.. } false { document.else if.. var sum=0.

write("Febuary").write("July"). break case(n="2"): document. break case(n="8"): . break case(n="6"): document.write("January").write("April"). </script> </body> </html> This example is display to all months in a year for using the switch case:- <body> <script type="text/javascript"> var n=0.write("June").write("March"). break case(n="4"): document. break case(n="3"): document. n=prompt("Enter a number between 1 to 12:") switch(n) { case(n="1"): document. break case(n="5"): document. break case(n="7"): document.write("May").</script> </head> <body> <script language="javascript"> showAlert().

Although all major browsers that are version 3.document.write("August"). This makes it difficult to create a complicated JavaScript code that work across all browsers. different versions of the same browser handle JavaScript differently. Object .write("September").write("November"). break default: document. It is a Case sensitive application. So always check your pages on as many different browsers (and even platforms) as possible.0 or higher include JavaScript code support. Now the biggest problem is the imperfect JavaScript implementations that today's browsers offer.write("December").based Scripting language for Client and Server applications.platform. JavaScript is different from the Java language. break case(n="9"): document. break } </script> </body> Conditions In Java Script About JavaScript Java Script is Netscape's Cross . In fact. JavaScript programs are usually embedded directly in HTML files. The script executes when the user's browser opens the HTML file. The Simple Example to display the Sum of two Digits :- <html> . break case(n="11"): document. break case(n="10"): document. they deal with JavaScript differently.write("October").

val2=10. we take the value 20 and 10 in val1 and val2. JavaScript loops Very often write code. It can be used to any number of JavaScript Statements. The Instead of adding several almost equal lines in a script we can use loops to perform a task.write is also a function to use print the Message and values.<head> <script language="javascript"> function showAlert() { val1=20.The while Loop . The result is 20 display on the Screen.write("sum="+(val1+val2)). Looping In Java Script What is JavaScript loop? The JavaScript loops used to execute the same block or code a specified number of times and while a specified condition. } </script> </head> </body> <script type="text/javascript"> showAlert(). document. </script> </body> </html> JavaScript code is embedded in HTML within a <SCRIPT> tag. you want the same block of code to run over and over again in a row.The For Loop 2. Document. JavaScript supported Two different type looping :1. showAlert() is a function to use in JavaScript language. Val1 and Val2 is a data type.

JavaScript loop Use a For loop to run time same block of code a specified the number..i<=6. The loop will be always execute a block of code once and then it will repeat the loop as long as the specified condition is true.while loop is a variant of the while loop. Example: <html> <body> <script language="javascript"> var i=0 for (i=0. This .write("<br />") i=i+1 } </script> </table> </body> </html> .write("serial number" + i) document. The do while loop The JavaScript do.i++) { alert("The number is " + i) } </script> </body> </html> The while Loop: The while loop is used when the loop to execute and continue executing while the specified condition <html> <body> <script language="Javascript"> var i=0 while (i<=10) { document..For Loop: The JavaScript for loop is used the know in advance how many times of the script should run.

write(" " .. even if the condition is false.loop will be always executed once. The javascript for.7.5.10). document.in loop is used to provide to the enumerate properties of a JavaScript object . Example: <html> <body> <script language="Javascript"> var i=0 do { alert("number" + i) i=i+1 } while (i<3) </script> </table> </body> </html> The for in: This is not same as the for loop . var num= new Array(8.write("<br />") } </script> </head> </body> .num[i]). This loop only found in JavaScript . Example: <html> <head> <Script language="Javascript"> var i. because the loop code are executed before the condition is tested. This statement in the loop are executed for each property of an object until every property has been accessed. for(i in num) { document..4.

write("value" + i) document.Break and continue Break: The JavaScript break command will break the loop and continue executing the code the follows after the loop.i<=6. Example: <html> <head> <Script language="Javascript"> var i=0 for (i=0.</html> Javascript looping Break and continue There are two statements supported in javascript used in loop:.i++) { if (i==3){break} alert("number" + i) } </script> </head> </body> </html> Continue: The JavaScript continue command will be break the current loop and continue with the next value.write("</br>") .i++) { if (i==4){continue} document. for (i=0. Example <html> <head> <script language="JavaScript"> var i=0.i<=8.

The syntax of JavaScript function is as follows: function fname(prameter1. All the java script code are written inside the curly braces.. .... In the JavaScript semicolon is optional but its better to put semi-colon as part of best practices. If you write function in uppercase the code will generate error.) { JavaScript code 1 JavaScript code 2 . } While defining JavaScript function its important to remember that the keyword function should be in lowercase other wise JavaScript won't understand it as function.} </script> </head> </body> </html> JavaScript Functions What is JavaScript Function? Java script Function is nothing but it is a reusable code-block that is execute when the function is called.. Function is defined in the head section of the code.parameter2. } </script> </head> <body> <form> <input type="button" value="Click Here!" . Example: <html> <head> <script language="javascript"> function showmessage(){ alert("How are you").

} brackets.. Functions are written inside the head section of the html document. It is used to group many JavaScript codes under one name. The alert function displays the message "How are you".. because function does not execute when the page loads. Built-in functions . For example you can write a function to validate email address. when you clicked on the button ("Click Here"). What is the use of JavaScript Functions: The java Script Function is very useful in writing the JavaScript code.onclick="showmessage()" > </form> </body> </html> Function starts with the function keyword and code of the function is enclosed in {.

JavaScript provides many built in functions that ease the development of JavaScript programs. and ask the user to determine from the two option . The out put of the function looks on the arguments given by you . The prompt() built -in function display the prompt dialog box. Example: <html> <head> <script language="javascript"> function myfunction(text) { confirm(text) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Do you want to delete it!')" value="Delete"> . The write() built in function used to write something on the document. The confirm() built-in function display the confirmation dialog box. The focus() built -in function built the pointed object active and put the curser on the text field. Inquiring the user for input. Here are the list of the built-in JavaScript functions: JavaScript Build in Function alert() confirm() focus() indexOf() prompt() select() write() Function Description The alert() built-in function displays the alert dialog box. The select() built -in function used to select the pointed object. Function arguments: Through variable you can pass argument to function.

<input type="button" onclick="myfunction('Do you want to save it!')" value="Save"> </form> </body> </html> .