80 likes | 345 Views
Lecture 4: Javascript Basics. Javascript is a scripting language based on pieces of C, C++, shell scripts, Pascal, Java, etc. Scripts – loosely typed C++ - object oriented ideas Pascal – some syntax elements C – much program syntax and semantics Java – no pointers
E N D
Lecture 4: Javascript Basics Javascript is a scripting language based on pieces of C, C++, shell scripts, Pascal, Java, etc. Scripts – loosely typed C++ - object oriented ideas Pascal – some syntax elements C – much program syntax and semantics Java – no pointers Check this example out…. Program
Example source code <html> <head> <title>testing javascript</title> <body> <P><h1>This is a Javascript example. It adds two numbers and then pr</h1> </p> <script language = "Javascript"> var i=1 ; while( i < 1000000) i+=1; window.alert("Fatal system error. Restart your computer now?"); </script> </body> </html>
Javascript basics Declaring variables: var keyword, typeless variables Basic I/O: document.writeln( ); window.alert( ); window.prompt( ); Type conversion: parseInt( );
Another example <html> <head> <title>testing1.html</title> <body> <script language = "Javascript"> var number1, n1,n2, number2, sum; number1=window.prompt("enter number 1", "0"); number2=window.prompt("enter number 2", "0"); n1 = parseInt(number1); n2= parseInt(number2); sum = n1 + n2; document.writeln("<P>Sum is "+sum+"</P>"); </script> </body> </html>
Control structures Boolean expressions for loops while statements if then else switch statements
Another example <html> <head> <title>testing1.html</title> <body> <script language = "Javascript"> var n1,n2,counter=0,i, piest = 0, // quadrant =new Array(4); sum=0; counter=window.prompt("Enter the number of desired samples:","100"); counter=parseInt(counter); for (i=1 ; i<=counter ; ++i) { n1=(Math.random()-0.5)*2; n2=(Math.random()-0.5)*2; if ((n1*n1)+(n2*n2) < 1) piest +=1; }; sum=(4*piest/counter); document.writeln("The estimate of pi is "+sum); </script> </body> </html>