760 likes | 1.02k Views
Intro to Javascript & DOM. Javascript Outline. Introduction Variables & data types Control Statements Arrays Functions Objects. Javascript Quick facts. Netscape was battling with IE and wanted a lightweight component to compete with Microsoft VB.
E N D
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Javascript Quick facts • Netscape was battling with IE and wanted a lightweight component to compete with Microsoft VB. • Created by Brendan Eich(creator of mozillafoundation)in 1995 while at Netscape. CSE 3345
Javascript Quick facts • Javascript was described by Brendan as, “something that had to ‘look like Java’ only less so and be Java’s dumb kid brother or boy-hostage sidekick.” • Had to be created in 10 days, or something worse would have been developed. CSE 3345
Javascript Disclaimer • A lot of people hate javascript! • A lot of the people that hate javascript really just don’t understand it. • There are good parts and bad parts. CSE 3345
3 Ways Use JS • Inline • Embedded • External CSE 3345
Inline Example <div onclick="alert('this is a horrible idea');"> Click me </div> CSE 3345
Embedded Example <html> <head> <scripttype="text/javascript"> window.onload=function(){ alert('window loaded');}; </script> </head> </html> CSE 3345
External Example index.html <html> <head> <!-- Make sure you always use an opening and closing <script> tag; else your script might not load --> <scripttype="text/javascript"src="test.js"></script> </head> </html> test.js window.onload=function(){ alert('window loaded');}; CSE 3345
Same as CSS • Reasons to use each method are the same as CSS. • External is preferred! CSE 3345
JS characteristics • It is a dynamic and weakly typed language. • Dynamic type means that there are no compile time checks to deduce variable type and type conversions. • Weakly typed mean the language will figure out for itself how to convert variables of different type. CSE 3345
Strongly Typed Example Test.java: publicclass Test { publicstaticvoid main(String args[]){ String x ="2"; intnum=7; num+= x;// Integer.parseInt(x); System.out.println(num); } } Test.java:6: error: inconvertible types num += x;// Integer.parseInt(x); ^ required: int found: String 1 error CSE 3345
Weakly Typed Example var x ="2"; varnum=7; num+= x; console.log(num);//72 CSE 3345
Outputting text to the console • The web console provides a heads up display for the web by letting users see error messages and other logged information. • console.log() – Outputs a message to the web console. Extremely useful for debugging!
Outputting text to the console Print strings console.log(“Hello “ + “world!”); Print objects var foo = ‘hello’; var bar = 0x01; console.log(foo + “ “ + bar + “!”);
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Declaring variables • Variables are declared using the var keyword. • Javascript does not allow variables to be declared with a specific type (int, float, boolean, etc). • Javascript does have different data types
Javascript types typeof4;// number typeof0xFF;// number typeofx;// undefined typeoftrue;// boolean typeof"String";// string typeof{};// object typeof[];// object typeoffunction(){ alert("hi!");};// function
To var, or not to var? • Any variable declared without the varkeyword becomes a global variable. • That means un-varred variables in methods automatically are global. CSE 3345
Truthy and falsy values Any value can be converted to a boolean according to the following rules: • false, 0, the empty string (“”), NaN, null, and undefined all become false. • All other values become true. CSE 3345
Truth and Falsy in Action var c =(false==0);// true var d =(false=="");// true var e =(0=="");// true //null and undefined are only equal to themselves and each other var f =(null ==false);// false var g =(null == null);// true var h =(undefined == undefined);// true vari=(undefined == null);// true //NaN is not equivalent to anything var j =(NaN == null);// false var k =(NaN == NaN);// false CSE 3345
Comparing for equality • The Equals operator is ==. Compares “truthy” and “falsy” values of variables. • Strict equals operator is ===. Always returns false when the operands are of different types. CSE 3345
Always use === • To avoid unintended results, always use the strict equals operator. CSE 3345
String operators • Use the + operator to concatenate two strings together. var x = “hello” + “ world”; • Use the += operators to append two existing strings. var x = “hello”; x += “ world”; CSE 3345
Converting strings to numbers • parseInt() – parses a string object and returns an integer of the specified radix or base. You should always specify a base. • parseInt(“010”, 2);// 2 • parseInt(“010”, 10); // 10 • parseFloat() – parses a string object and returns a floating point number. Always uses base 10. • parseFloat(“10.44”); //10.44 CSE 3345
Converting strings to numbers • You can also prepend a string with a + to convert the string to a number. varstring="50"; console.log(string+100);// 50100 console.log(+string+100);// 150 CSE 3345
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Control Statements • Javascript supports the typical list of control statements. • if, else, else if • while • do while • for • switch • break • continue CSE 3345
Control Statements • In addition to that list, js has a “for in” statement. • Use it to iterate over properties of an object. • Be careful using “for in” for arrays. Sometimes an object will have properties that you’re unaware and give weird output. CSE 3345
For in example // Initialize object. a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"} ; // Iterate over the properties. vars = "“; for(var key in a) { s += key + ": " + a[key]; s += "<br />"; } document.write(s); // Output:// a: Athens// b: Belgrade// c: Cairo CSE 3345
Bad Part of Javascript • Always place an opening brace “{“ on the same line as the control statement or function. • Undesired results can occur if you don’t follow this practice. • See here for details CSE 3345
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Arrays • Arrays are a special type of object that have a length property. • Accessing a value that is outside of the array bounds returns undefined. • The length property returns the length of the array. • The length is also one more than the highest index. • The length of an array isn’t always the number of items in the array. CSE 3345
Array Length Bad Part var x =["dog","cat","monkey"]; x.length;//3 x[100]="aligator"; x.length;//101 CSE 3345
Bad Array Initialization > var a = new Array(); > a[0] = "dog"; > a[1] = "cat"; > a[2] = "hen"; > a.length 3 > var a = new Array(); //bad CSE 3345
Good Array Initialization > var a = ["dog", "cat", "hen"]; > a.length 3 > var a = []; //good CSE 3345
Array Methods CSE 3345
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Functions • Almost like typical C/C++ and Java functions, except you don’t specify a return type. function sayHello() { alert(“hello world!”); } CSE 3345
Function with parameters • Once again similar to C/C++ and Java, but you don’t specify the data type of the parameters. • You also don’t prefix the parameter name with the var keyword. function add(x, y) { return x + y; } CSE 3345
The arguments object • The arguments object is a local variable available within all functions that contains an entry for each argument passed to a function. • The arguments object will also hold values for parameters that are specified by the function. CSE 3345
Arguments object example functionconcat(parm1){ varstr= parm1; for(vari=0,len=arguments.length;i<len;i++){ str+=" "+ arguments[i]; } returnstr; } concat("1","2","3","4"); //"1 1 2 3 4” CSE 3345
Anonymous Function • You can create functions that are not bounded to an identifier. alert((function(){return "hello";})()); CSE 3345
Functions are first class objects • This means that javascript functions are just a special type of object that can do all things regular objects can do. This allows • Functions to be stored as variables • Functions to be passed as a parameter to another function. • You can return a function from another function. CSE 3345
Functions stored as variables functionsayHi(){console.log(“hi”);} var hi =sayHi; hi();// hi • Note that when assigning a function to a variable, you don’t place “()” after the function name. • However, to execute the function with the variable name, you must use “()”. CSE 3345
Function as a parameter of another function functionsayHi(){return"hi";} functionsalutation(greeting, name){ console.log(greeting()+" "+ name); } varhi =sayHi; salutation(hi,"Fred"); // hi Fred CSE 3345
Function as a return value for another function functionadd(x,y){return x + y;} functionsubtract(x,y){return x - y;} functiongetOperation(x){ var operation = x %2===0? add : subtract; return operation; } var operation =getOperation(2); operation(5,3);// 8 CSE 3345
Javascript Outline • Introduction • Variables & data types • Control Statements • Arrays • Functions • Objects
Objects • Objects are a collection of name-value pairs • The “name” part is a javascript string. • The “value” part can be any javascript value. CSE 3345
Creating Objects var student ={ name:"Wade Wilson", alias:"wwilson", id:12345678, email:"wwilson@smu.edu", isPassing:true }; CSE 3345