Introduction to Javascript
What is javascript? The most popular web scripting language in the world Used to produce rich thin client web applications Supported by all browsers Designed to make web pages more interactive A scripting language is a lightweight programming language where code lines are interpreted and executed “on the fly” without being compiled Syntax is similar to C
What can javascript do? Manipulates HTML CSS Validates and stores data Reacts to events Produce reusable web widgets Can be used to build complex, interactive desktop-like user interfaces that run in a browser
Including javascript on a page javascript can be included on the same page between tags alert(“My javascript alert message”); Hello World This is a paragraph
Including javascript on a page There can be an external link to a javascript file This is the preferred approach Allows packaging and reuse src can be an absolute url e.g. “ or a relative url “scripts/loader.js” Hello World This is a paragraph
Manipulating HTML text via javascript TEC 319 Web Page First Paragraph document.getElementById(“main").innerHTML="JavaScript is cool";
Writing directly to Document Output Test Web Page document.write(" Modified JavaScript Page ");
javascript syntax javascript is case sensitive statements always end in a semicolon ; document.getElementById(“name”).innerHtml = “John Doe”; Each javascript statement is executed sequentially in the order that it is written tags can be placed anywhere on the page but are normally placed between tags or at the bottom of the page for performance reasons
javascript comments // Used to comment out a single line /* Used to used for multiple lines to comment out an entire Block of text or code */
javascript variables Used as containers to store information var firstName=“Tim”; var lastName= “Smith”; var person = {firstName : “Time”, lastName : “Smith”}; var students = [“Jim Smith”, “Jane Adams”,”Henry Thomas”]; var name=“John”, age=30, job = “programmer”; If var is not used, then variables will be global in scope (i.e. they will be accessible to all other scripts)
javascript variables Are case sensitive (a and A are two different variables) Must begin with a letter, the $ character or an underscore
Local javascript variables These are declared using var When variables are declared this way, they become local and can only be accessed from within that function The variable has a local scope eg function displayGreeting(name) { var greeting = “Hello “ + name; document.getElementById(“greeting”).innerHtml = gretting; }
Global javascript variables These are defined outside of functions (or even inside functions) They are are accessible to all scripts and functions on the web page They are not prefaced by “var” e.g. multiplier = 10;
Javascript functions Often we want to control when javascript executes (i.e. in response to some event on a page) We can create functions to contain our scripts and call the function when an event occurs function myFunction() { document.getElementById("demo").innerHTML ="My First JavaScript Function"; } My Web Page A Paragraph Try it
Defining functions function functionName() { //function code goes here } Functions can contain arguments and can return values function add(num1, num2) { var sum = num1 + num2; return sum; //return num1 + num2; -- shortened version }
javascript datatypes Javascript is not a strongly typed language Some of the basic dataypes that exist include Strings var user = “ID34949”; Numbers var amount = 20; Booleans var isAuthenticated = true;
javascript datatypes Arrays var colors = [“red”,”green”,”blue”]; Can be accessed by their indices (0 based) colors[1] is “green” Objects var person = {firstName : “James”, lastName : “Smith”, id : “1234A”}; Object properties can be accessed by their indices person[“lastName”] is “Smith” Null or undefined var total; or var total = null; If value was never defined, then its value is undefined if(typeof name !== “undefined”) { //check to see that name is not undefined } or if (!name) { //check to see that name is defined and has a vale }
javascript arithmetic operators Given that y = 5
javascript assignment operators Given that x = 10 and y = 5
The + operator Can be used in addition or to add string variables or text values together var text1 = “Hello There.”; var text2 = “How are you?”; var text3 = text1 + “ “ + text2; The value of text3 is: Hello There. How are you?
The + operator var num1= 10, num2 = 15; var result = num1 + num2; The value of result is: 25 Other examples : x = 5 + 5; y = “5” + 5; z = “Hello” + 5; The result of x, y and z are: Hello5
Comparisons Given that x = 5
Logical Operators Given that x=6 and y=3
Conditional or ternary operators variablename = (condition) ? value1 : value2; if c0ndition is true, value1 will be the result if condition is false, value2 will be the result eg. var x = 12; var y = x >20 ? 5 : 10; var eligible = x<10 ? “no” : “yes”;
Conditional Statements if statement – used to execute code if only a specific condition is true if else statement – used to execute one condition or another if only two conditions are possible if else if…else statement – used to select and execute one of many possible options or conditions if they are present switch statement – used to select one of many possible outcomes
If statement if (condition) { //execute some code here } var x = 20; if( x < 25) { x = x + 30; }
If else statement if (condition) { //do some logic } else { // do alternative logic } var greeting = “”; if(hour <12) { greeting =“Good morning”; } else { greeting = “Good afternoon;” }
If else if … else if (condition) { //do some logic } else if { // do alternative logic } else if { //alternative logic } else { //final catch all condition } var greeting = “”; if(hour <12) { greeting =“Good morning”; } else if(hour < 18) { greeting = “Good afternoon;” } else { greeting = “Good evening”; }
Switch var count = 2; switch (count){ case 1 : //do some logic break; case 2: //do some logic break; default: //default logic here break; }
Looping For loop for (variable=startvalue;variable<endvalue;variable=variabl e+increment) { code to be executed } e.g. for ( var i=0; i < 10; i ++) { console.log(i); }
Looping While loop While (some condition is true) { //Execute some code } var i = 10, sum=0; while (i<20) { sum += i; i++; }
Looping do { code to be executed } while (variable<endvalue); Loop will always be executed at least once e.g. var i = 10; do { console.log(i);i++; } while(i<10);
Break statement Helps break out of a loop for (i=0;i<10;i++) { if (i==3) { console.log(“Got here!”); break; } i++; }
For in statement Allows you to loop over the keys of an object var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + “ “ + person[x]; } alert (txt);
Exception handling try { //Run some code here } catch(e) { //Handle errors here }
Throwing exceptions var x=prompt("Enter a number between 5 and 10:",""); try { if(x>10) { throw "Err1"; } else { alert(x); } } catch(err) { //handle exception here }