JavaScript: Introduction PV219, spring 2023 Agenda • JS Introduction • JS How To • JS Statements • JS Comments • JS Variables • JS Data Types • JS Objects • JS Arrays Agenda • JSJSON • JS Functions • JS Operators • JS Inspect Elements (Chrome, Firefox, IE) • JQuery • DEMO Introduction • JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers, PCs, laptops, tablets, smart phones, and more. • A scripting language is a lightweight programming language. • JavaScript is programming code that can be inserted into HTML pages. • JavaScript inserted into HTML pages, can be executed by all modern web browsers. • JavaScript is easy to learn. How TO • JavaScripts in HTML must be inserted between tags. • JavaScript can be put in the and in the section of an HTML page. OUTPUT • JavaScript is typically used to manipulate HTML elements.

My First Paragraph

Statements • JavaScript is a sequence of statements to be executed by the browser. • JavaScript statements are "commands" to the browser. • The purpose of the statements is to tell the browser what to do. • JavaScript code (or just JavaScript) is a sequence of JavaScript statements. • Each statement is executed by the browser in the sequence they are written. Statements • Semicolon; - Semicolon separates JavaScript statements. - Normally you add a semicolon at the end of each executable statement. - Using semicolons also makes it possible to write many statements on one line. document.getElementByld("demo").innerHTML=" Hello Dolly"; document.getElementByld("myDIV").innerHTML= "How are you?"; Statements • JavaScript is Case Sensitive - Watch your capitalization closely when you write JavaScript statements: • A function getElementByld is not the same as getElementbylD. • A variable named myVariable is not the same as MyVariable. Statements • Block Statement i statement_l; statement 2; statement_n; j_ • Example while (x < 10){ x++; } Statements • Conditional Statements - if...else Statement - switch Statement if (condition) statement_l lelse statement 2] switch (expression) ( case label_l: statements_l (break;] case label_2: statements_2 [break;] ♦ • • default: statements_def (break; ] Statements • LOOPS - for Statement - do...while Statement - while Statement - break Statement - continue Statement Statements • Object Manipulation Statements - for...in Statement var obj = {make:"BMW", model:"2013"} function dump_props(obj, obj_name) { var result = ""; for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "
"; } return result; } document.write(dump_props(obj,"obj")); Comments • Comments will not be executed by JavaScript. • Comments can be added to explain the JavaScript, or to make the code more readable. • Single line comments start with//. • Multi line comments start with /* and end with */. Comments // Write to a heading document.getElementByld("myHl").innerHTML="Welcome to my Homepage"; /* The code below will write to a heading and to a paragraph, and will represent the start of my homepage: */ document.getElementByld("myHl").innerHTML="Welcome to my Homepage"; var x=5; // declare x and assign 5 to it Variables • JavaScript variables are "containers" for storing information. • As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y). • Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume). - Variable names must begin with a letter - Variable names can also begin with $ and _ (but we will not use it) - Variable names are case sensitive (y and Y are different variables) var money; var name; Variables • JavaScript Data Types var name = "Ali"; var money; money = 2000.50; • Global & Local Variables var myVar ■ "global"; // Declare a global variable function checkscope( ) { var myVar - "local"; // Declare a local variable document.write(myVar); ) Variables • One Statement, Many Variables var lastname="Ahmad", age=30, job="carpenter"; var lastname="Mohammad", age=30, job="Engineer" ; • Value = undefined - In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined. var lastname; Data Types • String, Number, Boolean, Array, Object, Null, Undefined. • JavaScript has dynamic types. This means that the same variable can be used as different types: var x; // Now x is undefined var x = 5; // Now x is a Number var x = "Salin"; // Now x is a String Data Types • JavaScript Booleans - Booleans can only have two values: true or false. var x=true; var y=false; • JavaScript Arrays var arr = new Array(); arr[0] = "item 1"; arr[l] = "item 2"; var arr = new Array("iteml","item2"); var arr = ["iteml", "item2"]; Data Types • JavaScript Objects - An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas: var person={firstname:"James", lastname:"Bond", id:9999}; var person={ firstname : lastname : id : }; James" Bond", 9999 Objects • JavaScript is designed on a simple object-based paradigm. "Everything" in JavaScript is an Object: a String, a Number, an Array, a Date.... • In JavaScript, an object is data, with properties and methods. - Properties are values associated with objects. - Methods are actions that objects can perform. Objects • Accessing Object Properties objectName.propertyName • Accessing Object Methods objectName.methodName() Objects • Objects in JavaScript, just as many other programming languages, can be compared to objects in real life. var myCar = new Object(); myCar.make = "Ford"; myCar.model = "Mustang"; myCar.year = 1969; myCar.make myCar["make"] Objects var myCar = {make:"BMW",model: "s2013",year:"2013"} function showProps(obj, objName) { var result = ""; for (var i in obj) { if (obj.hasOwnProperty(i)) { result + = objName + "." + i + " = " + obj[i] + "\n"; } } return result; alert(showProps(myCar,"myCar")) Arrays • The JavaScript Array global object is a constructor for arrays, which are high-level, list-like objects. • Arrays are list-like objects that come with a several built-in methods to perform traversal and mutation operations. Neither the size of a JavaScript array nor the types of its elements are fixed. Since an array's size can grow or shrink at any time, JavaScript arrays are not guaranteed to be dense. Arrays JSON • JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language var myJSONObject = 1 "bindings": 1 {"ircEvent" j "PRIVMSG", "method": "newURI", "regex": Ahttp://.*" }, {"ircEvent" s "PRIVMSG", "method": "deleteURI", "regex it : "^delete. *"}, {"ircEvent" . "PRIVMSG", "method": "randomURI", "regex ] }; it : random. * "} myJSONObject.bindings[0].method // "newURI" Functions • Function is a "subprogram" that can be called by code external (or internal in the case of recursion). Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function can return a value. • Every function in JavaScript is actually a Function object. Functions /• Declare the function 'myFunc' •/ function myFunc(theObject) t theObject.brand - "Toyota"; » /« • Declare variable 'mycar'; • create and initialize a new Object; • assign reference to it to 'mycar' •/ var mycar » t brand: "Honda", model: "Accord", year: 1998 \i /• Shows 'Honda' •/ window.alert(mycar.brand); /• pass object reference to the function •/ myFunc(mycar) ; f* • Shows 'Toyota' as the value of the 'brand' property • of the object, as changed to by the function. •/ window.alert(mycar.brand); Operators • Assignment operators • Comparison operators • Arithmetic operators • Bitwise operators • Logical operators • String operators • Special operators Operators: Assignment Shorthand operator Meaning 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 x «- y x - x « y x »- y x - x » y x »>- y x - x »> y x 4- y x - x « y x A- y x - x * y x 1- y x - x 1 y Operators: Comparison Operator Equal <--) Not tqualC-) Description Returns true If the operands are equal. Returns true if the operands are not equal Examples returning true 3 — var: •3- — wl 3 — '3' Strict equal (—) Returns true If the operands are equal and of the same type. See also Go Strict not equal (•—) Returns true If the operands are not equal and/or not of the same type )ect..i*. 3 —- varl I- 4 varj !- «3» varl varl !— -3- 3 t— '3' Greater than (>) Returns true if the left operand is greater than the right operand. var2 > varl •ia* > a Greater than or equal <> ) Returns true if the left operand is greater than or equal to the right operand. var2 >- varl varl >- 3 Less than {<) Returns true if the left operand is less than the right operand varl < var2 "Xi" < *2* Less than or equal (<-) Returns true If the left operand is less than or equal to the right operand. vail <- var3 var? <- S Operators: Arithmetic Operator Deicr.ption Ixampta fcnatv WfUte Return the integer remainder of dMdlng the two operandi 12 Xf return* 2. Dncremem) Lrjr» ooe'itor. Addi one to rt» operand If uted » * prr »et» • to 4 and returm 4 whereat •• • return ] and. only then, tett • to 4. (DecreireMl Unary operator. Subtractt on* from Hi operand The return value ll analogout lo that lor the «crement operator K . K 3. then > »et» • to J and returm 7. whereat • - returm 1 and. only then, »et» • to 2 Unaey operator. Return t the negation ol dt «s» iru» *h«mnv«. itiumt f*h* (LOQKit OK) Kttumi nprl iMunb« convtntd to in»«. olKrnwtr. r*tumi Thu». «*w«i ut«d inch leotovi viluti, rctumt im* H »Ittin op»r»fx) n if_. II boii t'T Iii*», mumi llk» (Log>ul *tOT) triwm l»>t« i» n» v«»gl« octt'irxj un b» (omtittd lo in* oth«fwn«. »«turnt im«