New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Entire Term Notes - Spring 2015

by: Miranda Jacoby

Entire Term Notes - Spring 2015 CIS 111

Marketplace > University of Oregon > CIS 111 > Entire Term Notes Spring 2015
Miranda Jacoby
GPA 3.2
Intro Web Programming
Patrick Holleran

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Patrick Holleran Intro to Web Programming notes for the term. Pretty easy class overall but the notes are needed in order to pass the test - open note tests but only allowed to have one sheet of no...
Intro Web Programming
Patrick Holleran
75 ?




Popular in Intro Web Programming

Popular in Department

This 44 page Bundle was uploaded by Miranda Jacoby on Monday September 28, 2015. The Bundle belongs to CIS 111 at University of Oregon taught by Patrick Holleran in Spring2015. Since its upload, it has received 167 views.

Similar to CIS 111 at UO

Popular in Subject


Reviews for Entire Term Notes - Spring 2015


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/28/15
CIS 111 Notes Wednesday April 1 l Operation of the world Wide Web A Operation of WWW and your web browser 1 2 3 4 Browser reads interprets and displays HTML CSS and JavaScript Displays results independent of source of code Write code and display on local machine Move code to server display on local machine ll File Systems on Local Machine and Server A Folder structure on local machine your computer or lab computer B Directory structure on UNIXbased server shelluoregonedu 1 Once everything is right in your own folders move into the directory lll SSH secure shell Interacting with the server A OS X built in 1 Terminal App in Utilities Folder B softwarecarpentryorgv4shelindexhtm IV Tranferring Files A Want to move files from your local file to the server B For both Mac and PC use CyberDuck 1 Open Connection a SFTP b server shelluoregonedu c usernamepassword duck id and password Drag and Drop files into CyberDuck Disconnect V Referring to External Resources A Remote Resources 1 located on another machine or another website 2 must use absolute references include host name and file spec B Local resources 1 created on or copied to local system same machine as current file 2 typically use relative references a makes sense because it is all on the local machine b relative references stay valid c This class all local resources Vl External Resources A Absolute references B Relative references used in this class 1 mycodejs A JavaScript file in the same folder as the HTML file 2 jsrandomjs A JavaScript file is the js folder library file 3 imagesstargif An image gif file in the images folder C Always use relative references for local resources 1 lose points for absolute references D Many web sites use the Apache HTTP Server software 1 U0 Web Server uses this software 2 On a site which uses the Apache server all Web pages stored in a user s publichtml directory Vll Accessing Student Web Pages A If the file is located at 1 shelluoregoneduhome10holleranpublichtml111examplesdemo7html B Address Web page at 1 http pagesuoregoneduholleran11examplesdemo7html C Eliminate the publichtml and change shell to pages CIS 111 Hypertext and HTML History and Hypertext and HTML A first concept expressed by Vannevar Bush in 1945 B Article As We May Think in The Atlantic magazine C The Memex D 1 instantly bring files and material on any subject First commercial application Hypercard 1987 Apple Computer Bill Atkinson Set of cards with information clicking on one card would bring up related cards and bring you to related stacks HyperTalk language WPFDNT Problem couldn t jump around to different computers Tim BernersLee at CERN 1 created first Web client and server in 1990 2 specified URL s HTTP HTML 3 First Web Browser WorldWideWeb early 1990s WWW was popularized by Mosaic Web browser from the National Center for Supercomputing Applications NCSA at the University of Illinois ll HTML and Web Pages A B Browsers read interpret and display Web Pages Web pages contain 1 text images videos control elements formatting information using Hypertext Markup Language HTML 3 formatting is specified using tags a words or symbols surrounded by angled brackets lt gt Start tags end tags and text they enclose an HTML element 1 lttitlegtDemo of DOMlttitlegt D Elements can be nested inside one another E All elements are nested inside the lthtmlgt lthtmlgt tag All HTML documents have two separate sections within the lthtmlgt tags 1 ltheadgt section info about document 2 ltbodygt section most of the content lll Text Display and Layout A B White space multiple spaces tabs blank lines not displayed by browser to set off paragraphs use paragraph tags 1 ltpgt text ltpgt C to start a new lines use break tag 1 ltbrgt D To force use of space use nonbreaking space character 1 ampnbsp E To draw horizontal lines use horizontal rule tag 1 lthrgt F various text sizes 1 lth1gt lth1gt lth2gt lth2gt etc IV Comments A comments may be used to communicate to the programmer but won t appear on the web page V Formatting Text A Old style 1 bold a ltbgt ltbgt 2 italic a ltigt ltigt 3 underline a ltugt ltugt Vl Hyperlinks A by default shown in color and underlined B specified using anchor tag 1 ltagt ltagt C Use a target to attribute to open in a new window Vll Display images A ltimggt tag B lmage that is displayed is located in a local or remote file 1 typically jpg gif or png file C Use src attribute to specify the location of the image file 1 ltimg src imagesstarpng gt D Always be in an image file never directly from the website VIII Displaying Lists A Unordered List B 1 ltulgt ltugt ordered 1 ltolgt ltolgt C actual items on the list 1 ltIigt ltIigt Tables A table tag B 1 lttablegt lttablegt table row tag to set off rows 1 lttrgt lttrgt C table data nested in rows for cells 1 lttdgt lttdgt Divs as containers A B other items can be places in containers called a ltdivgt attributes set for div applied to elements contained within it Monday April 6 History of the JavaScript Language A Netscape founded to develop commercial Web browser 1 founders Jim Clarck and Marc Andreessen 2 Developed Netscape Navigator browser in mid1990s JavaScript developed in May of 1995 by Brandan Eich 1 First available in Netscape Navigator 20 Support added in browsers from other companies 1 submitted to ECMA for standardization 2 development of Ajax propelled popularity Meant to provide interactivity and dynamism to Web pages 1 dynamism didn t bring you to a new webpage webpage just changed a ex searching on Amazon 2 designed to provide scriptability to Web page Learning value of JavaScript A W909 Just need a text editor and a browser to get started 1 text editor write the javascript 2 Browser interpret the JavaScript code and run the program Easy to see and share results on a web page connected to the internet Similar to other modern languages used for commercial development Popularity of JavaScript Usefulness of JavaScript Javascript similarities to other languages The C Family of Languages A C 1 Bell Labs C 1 Bell Labs Java 1 Sun Microsystems C 1 Microsoft version of C for net environment Objective C 1 Apple developers Swift 1 new language created by Apple PHP 1 serverside scripting language JavaScript 1 developed for clientside Web page scripting Where JavaScript can be used A Scripting Web Pages target in this class B In Javascript runners C D As a substitute for AppleScript in OS X 1010 Yosemite To creat OS X Dashboard widgets 1 JavaScript for Automation E F To create Windows 8NVindows Phone apps Serverside Web programming 1 using nodejs V Language Basics A B C JavaScript instructions in a text file JavaScript interpreter is built into Web browser Interprets instructions and produces output Vl JavaScript Language A B 7 me G Consists of statements to computer Each statement on a line lines can end with semicolons 1 statement 1 2 statement 2 OR 3 statement 1 statement 2 If more than one statement on a line must end with semicolon In this class end ALL lines with a semicolon Whitespace can be used as desired blank lines spaces etc Indentation can be chosen but will be specified for this course JavaScript is case sensitive varX is not the same as varx Vll Location of JavaScript A C within ltscriptgtltscriptgt tags in the ltheadgt or ltbodygt of HTML files 1 JavaScript processed before the full page is loaded In a separate text file by convention with a js suffix 1 ltscript src myscriptjs gtltscriptgt All javascript statements in this course must be in a separate file VlllComposition of JavaScript Statements A B Statements are usually made up of tokens JavaScript tokens 1 identifier name a name of something 2 punctuation a operators punctuation 3 numeric literal a value 4 string literal a value IX JavaScript Statements comments A W909 at the beginning of a line marks it as a comment and can mark the beginning and end of comments Comments are not evaluated by the JavaScript interpreter Serve as notes to the programmer or other programmers Also can be used to disable sections of code X Writing JavaScript in HTML format A B C Create your html file say xyzhtml Fill out the ltheadgt and ltbodygt sections in the file Create companion JavaScript file called xyzjs 1 note make sure you can see the extension on your computer D Write your JavaScript code in the js file Put the following line in the ltheadgt or ltbodygt of the html file 1 ltscript src xyzjs gtltscriptgt In this class the ltscriptgt tag goes in the ltheadgt sections G Load or preview the html file in your browser 1 remember to save the js file before loading or previewing 2 make sure you are previewing the html file Xl JavaScript Example producing output A B C a very simple JavaScript statement 1 alert Hello World Puts up an alert window with the specified text Called a function Xll Example 2 A another example 1 documentwrite Hello World writes to webpage XExample 3 A Writing output to the web console 1 consolelog Hello Console B writes to the web console C D called an object method Often used for debugging XlVExample 4 A B use the prompt command actually a function 1 prompt Enter some information Usually store the info returned for further use Wednesday April 8 JavaScript Variables W909 Variables are containers for storing information values Can set aside results of calculations or information for later use or reuse Stored information is dynamic Variables have names identifiers Names represent locations in computer memory Variables in Memory A B C Instead of using memory addresses variables can be given a name Using the name references the value stored in memory example When programmer refers to age is referring to value 18 Variable naming rules and conventions JavaScript A B C Names can contain ONLY letters digits underscores and dollar signs Names must begin with a letter underscore or sign Some allowable names 1 name size length1 coursedistance var2 traveltime variable1 2 not allowed 2var myvar radius onetwo oaccepted student name 3 Can t use just one digit Names are case sensitive Often combine multiple words in lower camel case 1 first letter is lowercase new word is upper case 2 myVar windowSize firstName lengthOfWord Reserve upper camel case for special identifier constructor functions 1 First letter is uppercase and new word is uppercase 2 StudentObject DataWindow Use variable names that are suggestive to what they represent for when other people read your code Variable names cannot use JavaScript reserved words 1 use lower camel case to avoid using a reserved word Declaring Variables A Before you use a variable you must declare it 1 JavaScript interpreter sets aside space in memory for values it will hold Declare a variable with a keyword var 1 varage 2 var myValue Can declare multiple variables in a single line of code 1 var height weight distance On exercises point will be deducted if var keyword is not used 1 program may still work without declaring the variable but points will be deducted 2 can use the variable and then declare it later in the code but will also lose points Assigning Values to Variables A B Values are given to variables using the assignment operator syntax 1 age 18 a means age gets the value of 18 2 customerName Joe Smith a means assign the value Joe Smith to customerName Giving a variable its first value is called initializing Can delayer and initialize a variable in the same statement 1 var heightOfWindow 50 a declare heighOfWindow set value to 50 Variables can be given new values they are variable 1 var i 10 2 i 20 a value of i is now 20 The value of one variable can be assigned to another 1 varxy 2 x 10 3 yx a value of y is now 10 VI Types of Data A W909 VII Igvrnrn Variables can be assigned different types of values Primitive types numbers strings booleans JavaScript is untyped don t have to specify type of the variable Can store any type of information in a variable Can change the type of information in a variable 1 var x 10 2 x oak a value of x is now Oak Types of Data number A B numbers values that can be manipulated mathematically numbers can be integers 1 var x 20 2 var cubicleHeight 5 numbers can have floating point values 1 var distance 217 2 var circleDiameter 735627 hexadecimal numbers can also be specified 1 var someNumber Ox12cfe121 2 always prefix the number with Ox 3 won t use in JavaScript JavaScript stores numbers as 64bit values Stored as binary data in memory Actually number stored in bits 051 exponent in 5262 sign in bit 63 64 bit storage limits size and precision of numbers 1 beyond 1e308 treated as infinity 2 beyond 1e323 treated as O 3 also limited precision represent 17 significant digits VlllTypes of Data string A string text sequence of characters enclosed by quotes single or double 1 var lastName Jones a strings are enclosed in quotes 2 color red a single or double quotes can be used B Strings can be any length 1 var firstLetter a C To include a quote in a quoted string must escape the character precede it with the escape character D cannot put carriage returns in the middle of a string new line character E New strings can be created by concatenating other strings Strings are concatenated using the operator 1 var myString Hello there a myString is Hello there 2 var count one two three a count is one two three G Note the difference between a number and a string containing a digit 1 var aNumber 7 a aNumber is a number 2 var aString 7 a aString is a string H Note the difference between a string and an identifier ex variable name 1 var myVar fox a assign string fox to variable myVar 2 var aVar fox a assign value of variable fox to a Var lX Types of Data Boolean A boolean variables 2 values true or false 1 var theVar true 2 var anotherVar false B Value is true or false commands in JavaScript not the string true or false C Often used as a test for conditional execution and conditional repetition D George Bool X Types of Data A Other types of values that can be assignment to variables 1 function 2 statement Xl Constants A F G In addition to variables data can be stored in constants B Uses keyword const C D Data in variables can be changes Initialization must be done in statement with declaration 1 var x 10 2 x 20 a value of x is now 20 Once assignment variables in constants cannot be changes 1 constx1O 2 x 20 a value of x is still 10 Prevents inadvertent changing of values that shouldn t be changed Use of var or const is the programmers choice XII The JavaScript Runner Environment A B C Simple JavaScript can be run and evaluated in runner environments Example Oregon JavaScript Runner page link in Course Resources Example JSTalkMac Application Monday April 13 JavaScript Operators Statements Expressions and Literals A B Statements 1 provide instructions to the computerinterpreter 2 each statement ends with a semicolon 3 may be made up of one or more expressions 4 examples a var theName b documentwrite Here is some output Expressions 1 section of JavaScript code which can be evaluated 2 when evaluated an expression returns a value 3 expressions can be made up of expressions 4 an entire statement can be an expression 5 examples a var a 10 b var b a 1 a is an expression when evaluated it returns 10 c var words These are some words 1 right side of the is an expression returns 1 string Literals 1 a literal is a basic value 2 for now a number string or boolean value 3 no evaluation is needed or performed 4 examples a 7 b 215 C hello d true e false ll JavaScript Operators A W909 Operators available for particular kinds of values combine values of 1 or more operands to produce a new value Types Unary 1 operand Binary 2 Ternary 3 Most often there are 2 operands Various kinds of operators NFDSquot39gtFD3 mathematical assignment relational logical bitwise string concatenation other lll Mathematical Operator A B the operands of mathematical operators are numbers addition operator produces the sum of 2 numbers 1 32 a evaluates value of 5 X 32 a x is assignment the value of 5 var myVar 5 var myOtherVar 2 var mySum myVar myOtherVar a mySum is assignment the value of 7 simple JavaScript code can be evaluated in JavaScript Runner subtraction operator produces the difference between 2 numbers 1 32 a evaluates to a value of 1 z216 a z is assigned the value of 15 multiplication operator produces the product of 2 numbers 1 57 a evaluates the value of 35 var z 53 a z is assignment the value of 15 division operator produces value of 1st operand divided by second 1 248 a evaluated to a value of 3 2 248 a z is assigned the value of 3 z 270 a results in infinity o modulus operator produces remainder after 1st operand is divided by the second 1 73 a evaluates to a value of 1 2 var z 248 a z is assigned the value of 0 no remainder H Increment and decrement operators 995 10 called unary operators as there is a single operand combines mathematical operation and assignment useful because incrementing and decrementing is common can be used as prefix before the variable or postfix after the variable operator adds 1 to the operand a varx7 y 10 b X 1 same as x x1 value of x is now 8 C y 1 same as yy1 value of y is now 11 operator subtracts 1 from the operand adds value of right operand to value of the variable on the left assigns to left a var x 7 b x 11 1 same as x x 11 value of x is 18 subtracts value of right operand from value of variable on the left assigns to left a var y 7 b y 5 1 sameasyy5 valueofyis2 multiples value of left operand by right operand and assigns is Other Unary Operators a typeof returns type of data contained by a variable 1 var x 7 2 typeof x a returns number 3 var z Walter Boxer 4 typeof y a returns string Note that when you get data from a prompt or later an html textbox 1 the type of the data is string 2 should use operator to change string to a number c directly proceeding string changes sting to number 1 var someString 7 2 var length someString a length is 7 d directly preceding strings changes string to number and changes sign 1 var someString 7 2 var length soneString a length is 7 11 String Concatenation a combines string of left side with string of right side 1 var one This is a 2 var two typical sting 3 var combo one two a combo is This is a typical sting b Be careful when combining strings and number c number is converted to a string when strings and numbers combined 1 var double 77 a adds numbers 14 2 var double 7 7 a concatenates strings 77 3 var double 7 7 a concatenates strings 77 4 var double 7 7 a adds numbers 14 Wednesday April 15 I Relational Operators A Relational Operators take 2 operands B return a boolean value true or false C operator returns true when both operands are the same false otherwise 1 77 true 2 var myVar 7 myVar 8 false not equals operator returns false when bother operands are the same true 1 7 7 false 2 var myVar 7 myVar 8 true gt greater than operator returns true when 1st operand is greater than second otherwise false 1 8gt7 true 2 var myVar 21 myVar gt 30 false 3 for strings it works alphabetically z gt a lt less than operator returns true when 1st operand is less than second otherwise false 1 7lt8 true 2 for strings it works alphabetically a lt z a if first letter is the same evaluate second letter gt greater than or equal to operator returns true when the first operand is greater than or equal to the second otherwise false 1 7gt 7 true 2 var greeting Hello var anotherGreeting Hello greeting gt anotherGreeting true a true because the makes the first greeting greater than the second b anything is greater than a space lt less than or equal to operator returns true when the first operand is less than or equal to the second otherwise false 1 7lt 21 true 2 var greeting Hello var anotherGreeting Hello greeting lt anotherGreeting true Logical Operators A Most logical operators are binary operators B Logical operators take operands which are boolean expressions return a boolean value true or false D values are often used in statements using conditional executions or conditional repetition Logical and ampamp returns true if both operands true false otherwise hFDNT true ampamp true true true ampamp false false false ampamp true fase var x 7 var y 21 x7 ampamp y 21 x7 ampamp y 3O xgt5ampampygt25 true fase fase Logical or II returns true if either operand is true false otherwise 1 2 3 true true true true false true false false fase not operator returns false if operand true true otherwise 1 2 true fase false true DeMorgan s Law 1 notA and B is the same as notA or not B not A or B is the same as notA and notB Converting ampamp to II a condf t1 onl ampamp condf 139 ton2 is the same as lcondftfonl condftfonZ Converting II to ampamp a condftfonl condfftonZ is the same as lcondftfonl ampamp condftfonZ Monday April 20 Conditional Execution l Terminology Punctuation Characters double quotes single quotes braces brackets parentheses 71 U1 F3 F 93 P angled brackets lt gt ll Conditional Execution A Previously all instructions are run in the order they are written B JavaScript provides the capability of determining whether or not to execute an instruction or block of code base on the value of an expression C The expression returns a boolean value D Several forms 1 itelse construction 2 switch statement 3 ternary or conditional operator lll Conditional Execution It statment A syntax it boolean expression statement 1 statement 2 Boolean expression returns a value of true or false Statements between called a code block and always enclose a block of code treated as a unit It expression is true statements in code block are run I expression is false the code is skipped Execution continues on the next line after the closing brace IQTlrnpow Do not need a semicolon after the closing brace Note use of indentation that is the convention C A convention is a practice generally used by experienced programmers K not necessary for the JavaScript interpreter but encourages creating of clean readable reliable programs M example var theScore prompt Enter your test score if theScore gt 59 documentwrite You passed ltbrgtltbrgt documentwrite Evaluation complete N Alternate Syntax on one line when statements are short 1 if boolean expression statement1 statement 2 2 example var theScore prompt Enter your test score if theScore gt 59 documentwrite You passed ltbrgtltbrgt IV Conditional Execution ifelse statement A syntax if boolean expression statement 1 statement 2 else statement 3 B Boolean expression returns a value of true or false C true gt code in the if block is run D false gt the code in the else block is run V Conditional Execution ifelse ifelse statement A syntax if boolean expression statement 1 statement 2 else if statement 3 else statement 5 B goes from if and then to else if and then to else 1 2 If boolean expression is false drop to next level If expression is true code is run C can have as many else ifs as needed 1 finish with an else Vl Conditional Execution Values as Booleans A When using conditional statements variables or numeric value convert to true or false they are treated as expressions 1 any number other than 0 is true 2 Oisfalse 3 example var x 10 message if x message It is true same as if x 0 else result It is false result B The following values are treated as false socalled falsey 1 900 5 O var xO undefined var x empty string var x NaN not a number var x 100 books null var x null Vll Conditional Execution switch statement A Syntax switch expression case valuel code block break case value2 code block break default default code block B example var theSchool prompt Enter your school var mascot switch theSchool case Oregon mascot Ducks break case Washington mascot Huskies break default mascot School not available VlllConditional Execution Conditional Operator A onthetes B Called Ternary Operator because is has 3 operands C sometimes written as D syntax boolean expression valuel valueZ E Operation 1 evaluates boolean expression 2 if true returns operand 2 value1 above 3 if false returns operand 3 value2 above F example var result var theScore prompt Enter your test score result theScore gt 59 You Passed You Failed document write result G Can always be written as an ifelse statement H conditional operator saves a little space Wednesday April 22 Cond onalRepe onLoops l Conditional Repetition A Previously instructions executed sequentially B However may need to repeat instructions 1 may keep repeating while a certain condition is satisfied 2 may repeats instructions a certain number of times C JavaScript provides several forms 1 while loop 2 dowhile loop 3 for loop While Loop A syntax while boolean expression statement 1 statement 2 Boolean expression returns a value of true or false if expression is true code is run if expression is false code block is skipped and always enclose a block of code treated as a unit At end of block control returns to top of loop where process is repeated QTWPQPU Note that if boolean expression is false the 1st time through the code block is never executed H Typically one of the statements in the block changes a term in the boolean expression l at the end of the final brace code jumps back up to while J example quotstartquot quotexitquot response promptquotEnter a wordquot var response while response documentwrite quotYou entered quot response quot Thank You ltbrgt documentwrite quotltbrgtDonequot lll Conditional Repetition Counter Variables A When looping a set number of times use Counter Variables B A counter variable keeps track of how many times the loop has been executed C Loop is terminated when the number reaches the desired value D E Syntax counter is the counter variable want to loop 10 times var counter 0 while counter lt10 statement 1 statement 2 counter syntax one line while boolean expression statement 1 statement 2 1 Works the same way as multiline format 2 typically use multiple lines and indentation if statements are lengthy 3 do not need the braces if there is only a single statement IV Conditional Repetition Flags A U1 F3 3 93 With while loops to simplify logic sometimes use flags A flag is a variable with a boolean value used to determine continuation of the loop Typically when the flag value is true the loop is done Flag value recomputed somewhere in the loop syntax done is the flag false false statement 1 var done while done statement 2 if boolean expression done true V Conditional Repetition dowhile loops A syntax do statement 1 statement 2 while boolean expression codeinl ockisrun THEN while statement is executed boolean expression returns a value of true or false E if expression is true control returns to top of code block code repeated F if expression is false execution proceeds to next line Vl Conditional Repetition for loop A syntax for statement 1 statement 2 statement 3 code block statement 1 code block statement 2 statement 1 executed before loop starts usually initializes counter statement 2 executed at top of each loop determines if loop continues statement 3 executed after each iteration of loop usually increments counter Separates loop maintenance initialization incrementation from other code This loop typically used if the number of iterations of the loop is known before it executes Probably the most heavily used type of loop by experiences programmers IQTlrnpow often used with arrays most heavily used loop C syntax for statement 1 statement 1a statement 2 statement 3 statement 3a code block 1 code block 2 K statement 1 and statement 3 can be multiple statements Vll Conditional Repetition Jump Statements A break 1 causes immediate termination of the while dowhile or for loop 2 usually subject to conditional execution 3 saw this before with switch statement B continue 1 causes end of current iteration of the loop 2 usually subject to conditional execution 3 resumes at top of code block Vllllnfinite Loops A condiiton to finish loops is never reached loop will continue to run may freeze the browser often occurs if nothing in the loop changes the variable in the boolean expression may require quitting the browser rnrnpow example var i 0 while flt20 documentwrftei 1 value isn t incremented Monday April 27 Func ons Func ons a function is a names block of code can contain any number of lines first the function is defined A B C D code can be run any time by using the name of the function E functions are called from other locations in the code F functions may or may not accept information when they are called G functions may not return a value to the caller H Functions may be 1 written by the programmer 2 always available from javascript builtin functions 3 imported from a library a collection of functions Functions Value code reuse write once use many times simplify code fewer lines and tokens elements of code simplifies maintenance enables large collaboration creation of building blocks Libraries can be provided and used repeatedly from multiple places 9mmpowgt Abstraction use without detailed understanding H key role can be used to assign response when something happens lll Functions Syntax A syntax for defining a function function functionname parameterl parametern code statements return returnva7ue B Parameters and return values are not required C Same rules apply to function names as to variables 1 names can contain letters digits underscores and dollar signs 2 names must begin with a letter underscore or sign 3 reserved words cannot be used fro function names 4 convention use of lower camelcase format with multiword combos D Simple function example function sayHelloltgt alert Hello E Note this function has no parameters and returns no value F Note also defining a function doesn t cause code to be executed it must be called Parameters A Some functions have parameters B Parameters values which are passed to and used by the function C a function can have any number of parameters D parameters included within parentheses separated by commas E a function with on parameter function sayHello theGreeting alert theGreeting F Note this function has a single parameter G Parameters used by the name specified in function definition a function with 3 parameters function orderMessage person item number item documentwrite person Thank you for your order of number J K When function is called parameters are passed in the order they are specified in the function definition ln JavaScript can pass in extra parameters without a problem Functions can also be written which use variable numbers or parameters V Functions return value A D E F a function with a return value function addNumbers numberl numberZ return numberl number 2 When a return value is provided is it returned to the called return may be followed by a literal or an expression return 7 return Thank you true varl 10 return return return can be included with no value just ends the function Function execution is ended with the return statement in encountered If no return statement function ends with the last statement Vl Functions local variables A 9000 E a function with local variables function circleArea radius var pi 31415 VdF dFEd area pi radius radius return area pi and area are local variables variables created within the function local variables are only available when the function is called go away when it finished this is called the scope of the variable here local scope parameters are treated and are used like local variables Vll Functions and global variables A B Local variables are only valid while the function is executing values assigned to local variables are discarded when the function completes gunman H to save information between invocations of a function must use a global variable global variables are declared outside the body of any function global variables can be accessed by any function or part of the program global variables retain their values while the program is running use only when absolutely necessary any part of the program could accidentally change the value of a global variable VlllFunctions UserDefined Libraries A functions may be useful in many places in a program which may be composed of many files it would be tedious to include the definition of the function in each js file solution define such functions in a single file called a library which can be accessed by many other files D typically stored in a directory called js accessed with the following html code ltscrfpt src jsmylfbraryjs gtltscrfptgt Wednesday April 29 Source of functions A B C written by programmer provided by JavaScript in a library Builtin functions A also knows as global functions Available any time JavaScript is used 1 does not require ltscrf pt arc xyz j s gtltscrf ptgt Function alert 1 syntax alert strfng Parameters any value resu none Displays an art dialog with a message 0quot39gtFJ 3 example alert test dfaiog window says test D Function prompt 1 syntax prompt message initial value 2 Parameters any value 3 result none 4 displays a prompt dialog with a message and initial value 5 returns value entered by the user 6 only available in the browser window environment E Function isNan 1 syntax result isNaNparameter parameters any value result boolean value determines whether parameter is an NaN not a number value 0quot39gtFJ 3 example var theResult 20 fred var x isNaNtheResult X true because this is not a number F Function isFinite 1 syntax result isFiniteparameter 2 parameters number 3 result boolean value 4 determines whether parameter is a finite number typically define to detect division by zero G Function parselnt 1 syntax resultparseintltparameter Parameters string Result number Converts a string to a number like 0quot39gtFJ 3 example var theResult parselnt 75 Math library object A provides a collection of useful mathrelated functions B Functions here actually are methods of the Math object syntax 1 Mathnameoffunctionparameter Includes functions like 1 abs X round x ceil x floor x 2 min xyzn max xyzn 3 powxy srtx Mathabs 1 syntax resultMath absparameter 2 Parameter number 3 Result number 4 returns the absolute value of the number Mathround 1 syntax result Mathroundparameter Parameter number result number return the value of the parameter rounded to the nearest integer 0quot39gtFJ 3 example var theResult Mathround5367 returns 5 Mathfloor and Mathceil 1 syntax result Mathfloor parameter result Mathceil parameter 2 floor rounds down 3 ceil rounds up Mathmin resultMathfloorparameter1 parameter2 parameterN 1 returns value of smallest number Mathmax 1 returns value of biggest number Mathpow 1 result Mathpowparameter1 parameter2 2 returns value of first parameter to the power of the second parameter Mathsqrt 1 returns square root or parameter L Mathrandom 1 parametersnone result number returns pseudo random number from O to but not including 10 cannot produce 1 0quot39gtFJ 3 Produce a random number from O to n var randomNumber Math random n 6 Produce a random number from min to max var randomNumber mfn Mathrandom maxmfn 7 Produce a random integer from min to max var randomlnteger mfn MathfioorMathrandom max mfn 1 IV Math Library Object MathPI vaiue of pf V Commercial Libraries A Elaborate libraries available to 1 simplify programming 2 extend functionality 3 handle things like browser incompatibilities B most popular is probably JOuery 1 Datepicker example 2 Fading and toggling exampling Vl Functions as Values A variables can be numbers strings booleans etc B Variables can also be assigned the values of functions Monday May 4 Objects and ObjectOriented Programming ObjectOriented Programming A a method of organizing your procedure and info B organized around data structures called Objects C Objects encapsulate state and behavior 1 state the values of variables and constants 2 behavior procedures which get set and manipulate those values D objects may model real world object or may not E Includes concepts of classes subclasses inheritance F advantages 1 efficient use of resources 2 protection against common programming errors 3 easier to understand for programmers and readers 4 helpful for collaborative and distributed effort ll History A E F G Simula 67 1 first language to feature objectbased capabilities Smammk 1 at xerox PARC well known early 00 language 2 designed by Alan Kay C Bjarne Stroustop Bell Labs 1 first popular OOL 2 extension of C with object capabilities Major current object oriented languages 1 C Objective C C Java JavaScript Swift Eventually replaced Procedural Programming built around functions Platformspecific extensions to language now usually exposed as objects frameworks APls Web page scripting API completely based of objects lll Classes and Objects A QTIWU Classes define types of objects 1 example twitter users An object is an instance of a class type 1 example Jane Jones a particular twitter user objects include the attributes and behaviors of the class 1 example class twitter users a attributes name account avatar b behaviors procedure for posting a tweet showing timelines 2 example object instance of twitter user a attributes Jane Jones jjones a picture of Jane b behaviors posting a tweet showing her timeline Create objects instances of particular object type or class after creation objects assigned to variables identified by variable name objects include all the attributes and behaviors of their class or object type Called properties and methods 1 property variable 2 method function IV Hypothetical example Rectangle Class A could have properties like 1 height 2 width 3 location xy 4 color 5 text Could have methods like 1 getArea 2 insetRect Could create a Rectangle myRect an object instance of class rectangle If myRect is a Rectangle object to access properties and methods someVar myRecthe1ght get the height myRectw1dth 250 set the wtdth theArea myRectgetArea get the area myRect1nsetRect 5050 change the stze V Hypothetical example Student class or object type A C D properties like 1 firstName 2 lastName 3 homeAddress 4 schoolAddress 5 major could have methods like 1 formatName 2 calculateGrade could create a Student aStudent an object instance of class Student If aStudent is a Student object to access properties and methods Vl Creating Objects A B Note most objectoriented language have a concept called inheritance 1 subclasses defined based on existing classes 2 inherit all of the classes and methods add others 3 Example StudentAthlete BandMember as subclasses of Student JavaScript for all practical purposes doesn t have class inheritance C JavaScript is a prototypebased language 1 objects inherit from other objects D In our class we ll define new object types independent of other object types 1 we ll ignore inheritance Vll Creating Objects hypothetical A step 1 define type of object or class 1 determine that properties variable it will have 2 determine the methods functions and define them write them 3 often put that definition in a library B alternately use an object type already defined C instantiate an object of a particular type 1 create variable of a particular type using a constructor function a var myObject new ClassName parameter1 parametern 2 use the object a someValue myObjectpropertyName get value of property b anotherValue myObjectmethodName call method VlllCreating and Using objects hypothetical A step 1 use a class already defined 1 class pet 2 properties type color weight 3 methods makeSound B lnstantiate an object of a particular class 1 create variable of a particular class using constructor function IX the Date Object A date objects represent dates and times B date is a typical builtin object you create objects of type class Date C objects are often created with the new operator 1 var today 2 new Date create a new Date Object representing now D new command invokes the constructor function which initialize properties 1 var otherDay new Date 2010 5 10 alternate form F full constructor function 1 var aDay new Date year month day hours minutes seconds milliseconds F call a method 1 aDaytoString returns the info about this date X Number object A numbers can actually be objects in JavaScript as well B can create a new number with the new command C U1 C C U 1 var myNum new Number 775234781 can pass a string and it will be converted is possible to a number 1 var myNum new Number 775234781 Wednesday May 6 Extending Objects A Users are not restricted to using the properties and methods of existing objects The programmer may add properties or methods to any object type Every object type has a prototype property which makes this possible Changes to CIassNameprototype are propagated to all instances of the type syntax CiassNameprototypenewProperty value CiassNameprototypenewMethod methodName Example with a Date object type instance of the Date class Dateprototypesay function alert Heiio var a Date new Date aDatesay could extend class after the object instantiated a more interesting example 5 DateprototypesayVaiue function documentwrite The date is thistoString var a date new date aDatesayValue ll Creating static properties A just add the property to the object type name NumberfavoriteNumber 18 favoriteNumber now static property of Number The refer to it anywhere you want to use it var someVariabie NumberfavoriteNumber someVariabie now has 18 Ill creating static methods A B C define a function just add the function to the object type name then call it anywhere you want to use it IV review A class in JavaScript type of objects created with a particular constructor function B class name constructor function name C To create an object of that class of that type 1 declare a variable and initialize it with the new command 2 use the constructor function and any parameters it requires var newVar new ClassName param1 param2 3 concrete example var mnyrthday new Date2001 5 23 V creating your own class or object type A programmers want to create their own objects for programming purposes there are several ways to do this one is use of a constructor function remember creating an instance of the date class WUQW other constructor examples var aNum new Number 7 var fsTF new Boolean 1 var myDate new Date 2010 10 25 F syntax of constructor function functfon Classname parameterl parameter2 thfsproperty1 parameter 1 thfsproperty2 parameter 2 thfsmethodName1 thfsmethodName2 aFunctfonName functfon code return value G Use of this keyword allows creation of properties and methods H Create an object which is an instance of that class var myObject new ClassName valuel value2 l Accessing properties ad methods of the object myObjectproperty1 myObjectproperty2 myObjectmethodName1 myObjectmethodName2 Monday May 11 l Arrays A a JavaScript data type which contains multiple variables B can contain any kind of values 1 numbers strings booleans functions objects 2 one array can contain multiple kinds of values 3 can also be empty C Elements in arrays are ordered there is a 1st item a 2nd etc D Arrays are objects they contain methods and properties 1 unlike numbers arrays are always objects ll Creating Arrays A Arrays can be created using simple assignments var myArray Chevrolet Ford Toyota B Arrays as objects can be created using the new keyboard var myArray new array Chevrolet Ford Toyota C Array elements are assigned indexes starting with 0 var myArray Chevrolet Ford Toyota Cadillac BMll D lndex indicates how far from the beginning of storage the element is lll Accessing Elements in Arrays A Array created in normal way var cars Chevrolet Ford Toyota Cadillac BMM B To access elements use array name H and the array index of the item var aCar cars0 var anotherCar cars2 C Can populates items using the array index and an assignment statement cars 5 Mercedes adds Mercedes as 5th element cars 1 Chrysler overwrite previous element D Can create sparse arrays arrays with empty slots cars 10 Mazda array expands to accommodate new item E another way to create and populate an array var towns J towns O Portland towns 1 Salem towns 2 Eugene F Arrays can have arrays as items 1 Called multidimensional arrays var multiD 123456789 2 dimensional multiD 0 1 multiD 1 2 2 6 var number var more G Functions as members of an array function sayHello alert Hello function sayGoodbye alert Goodbye sayGoodbye alert with Hello var myArray sayHello myArray 0 IV Associative Arrays A Instead of index numbers arrays can be created with other values as the index B these are called associative arrays C D example can create a keyvalue pair or dictionary where item can be looked up using a keyword var mascots l create empty array mascots Oregon Ducks populate the array mascots OSU Beavers mascots Washington Huskies V Arrays as Objects Properties A B C D As objects arrays have properties and methods Most often used property is length number of elements in array length will be 1 more than the highest index in the array Example var cars Chevrolet Ford Toyota Cadillac BMW numberOfCars carslength Therefore can always add an item to the end of the array like this carcarslength Pontiac Vl Arrays as Objects Methods A B much of the work done with arrays is done with the object s methods concau 1 syntax arrayconcatarray1array2array3 2 purpose returns array composed of concatenation or arrays 3 example var names1 Henry Susan Olive var names2 Sandy Earnest var allNames names1concatnames2 C indexOf 1 syntax arrayindexOfitemstart 2 purpose returns index of element in an array searches array returns 1 if element cannot be found 3 example var names 1 henry Susan var where names11ndex0f Susan returns 1 D join 1 syntax arrayjoinseparator 2 returns a string of elements joined by separator E IOOIOO 1 syntax arraypop 2 purpose removes last element of an array and returns that element 3 example 99 99 99 99 var beverages coke peps1 dr pepper alert beveragespop returns dr pepper alert beverages returns coke pepsi F push 1 syntax arraypush 2 purpose adds new element G reverse 1 arrayreverse 2 reverses order of array H sort 1 sorts items in an array l toString 1 returns array as a string J forEach 1 executes function for each element in an array Monday May 18 Domain Object Model DOM A maps out hierarchy keeps track of parents and children B Presents exposes HTML elements to the programmer as JavaScript objects 1 HTML elements gt JavaScript objects 2 HTML element attributes gt object properties and methods C Example 1 HTML ltimg src images mypicturejpg gt 2 Java Script mylmagesrc imagesmypicturejpg ll Useful HTML Elements A E F text field Editable text field 1 ltinput type text value default text gt 2 Key properties value textFieldNamevalue Button Standard push button which can be clicked 1 ltbuttongtTextltbuttongt 2 Key properties innerHTML buttonNameinnerHTML Paragraph Block of text set off by blank lines 1 ltpgtOne of more lines Div Container holding other elements rectangular area 1 ltdivgt 2 One or more line of text 3 ltdivgt 4 Key props innerHTML divNameinnerHTML lmg lmage displayed on screen jpg gif png etc Canvas Rectangular area for drawing with JavaScript lll Scripting web pages road map A access specific HTML elements as objects from the JavaScript code 1 How do access an image button or text box on my Web Page determine what cases things to happen when 1 when do I change the image on a web page Determine what happens when something occurs what 1 what happens on the webpage when a button is clicked Associate causes and effects when the page is loaded 1 How and when do I set up the connections between things that happen and their effects IV accessing HTML elements from JavaScript A JavaScript code needs to access some of the HTML elements on the page 1 may need to V Summary of Basic Steps A create web page assign values to an id attribute for elements involved B create js file with JavaScript code and include a ltscript src xyzjs gt element C in JS file write function or functions that perform the actions desired D create an initialization function in the class call it init which assigns functions to event handler properties of appropriate objects Wednesday May 20 l Scripting Web Pges A Full list of tags wwww3schoolscomtags B important tags 1 ltbodygt ltbu ongt ltimggt ltdivgt ltpgt ltspangt NQSNPPON lttextareagt 8 lttable lttrgt ll Scripting Web Pages Buttons A Represent a real world button Provides highlighting and animation when clicked Typically used by handling onclick event can change label of button by setting the innerHTML property W909 Note can always use the this keyword in an event handler to refer to the object for which the event is being handled the button here lll Scripting Web Pages Images A Displays an image loaded from the disk or network B typically handle onclick and onmouseover onmouseout events C Can change picture using the src property D could trigger change in enough HTML element E Sometimes used instead of button elements 1 picture look like a button 2 onclick event triggers action just like a button IV Scripting Web Pages ltdivgt A used as a container to hold other objects and treat them as a group V Scripting Web Pages ltspangt A usually contains text Vl Scripting Web Pages Tables A line up columns of info B sometimes used as menus with items in the cells Vll Scripting Web Pages text area VlllScripting Web Pages ltselectgt A pop up menu lX Scripting Web Pages Source of the event A wanted to connect more than one element to a handler 1 simplify and shorten the code B would probably need a way for determining when element triggered the event C one solution keyword this X Scripting Web Pages The event Object A Functions handling events may use the event object B is passed as the first parameter to any event handling function C properties include 1 target 2 time 3 name 4 view 5 the number of clicks Monday June 1


Buy Material

Are you sure you want to buy this material for

75 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.