Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Programming. What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers,

Similar presentations


Presentation on theme: "JavaScript Programming. What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers,"— Presentation transcript:

1 JavaScript Programming

2 What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers, servers, laptops, tablets, smart phones, and more”— w3schools.com Is there anything it is NOT for? Script that is interpreted by a Web browser Run on the client/browser (for most of the time?) Create dynamic/interactive HTML Differences from other programming languages –Embedded in HTML files –Haven’t found a good IDE (editing and debugging) yet

3 Major Programming Concepts Variables –Dynamic types (Numbers, Strings, Booleans, Objects) –Declaration –Scope Statements Branching Looping Functions –Parameters vs. arguments –Return 0, 1, or N values Objects –Built-in objects (examples in Chp. 8) vs. user defined –Attributes and methods Events

4 Example Code Changing heading and color based on even/odd seconds –DynamicHeadings.html Sort random numbers –SortRandomNumbers.html--functions inside the HTML file –SortRandomNumbersExternalJsFile.html--Functions saved in external.js file (RandomSorting.js local or in the cloud)

5 Using Firebug Handout Demo using example code

6 Exercise #4 Write a function DMS2DD(degrees, minutes, seconds) which should convert the degree, minute, and second components of a positive latitude/longitude coordinate (for example, 40 37 24) to decimal degrees and return the value Write a function DD2DMS(decimalDegrees) which should convert a positive latitude/longitude coordinate in decimal degree into degrees, minutes, and seconds components and return the values. (hint: use the Math.floor() function) Test the two functions with a html file. Use DmsDdConversionTemplate.html

7 Conversion Between DMS and DD DMS  DD DD  DMS

8 Exercise #4 Write a function GenerateRandomNumbers(n, min, max) which should generate n random integer numbers between min and max. Write a function FindMinValue(data) which should find the minimum value in the data Array. Test the two functions with a html file. Use SortRandomNumbersTemplate.html

9 Data are stored somewhere in computer memory as objects How to access the objects? Variables are names used to refer to the objects allow objects stored in computer memory to be accessed by names instead of addresses Using variables make abstract and reusable calculations DMS2DD: 34+45/60+30/3600 degrees+minutes/60+seconds/3600 Variables

10 Valid Variable Names Start with a letter and no space –Letters, digits, and underscores Punctuation characters are not allowed Reserved words are not allowed –return, if, else, … Avoid special variables—predefined variables –pi, … Case sensitive –classNum and ClassNum are two different variables

11 Mnemonic—name makes sense Write programs that they are easy to read Choice of variable names enhances code readability –May help detect bugs Follow a certain naming convention –classNum = 319, numOfStudents = 13 a=34degrees=34 b=30minutes=30 c=45seconds=45 d=a+(b/60)+(c/360)dd=degrees+(minutes/60)+(seconds/360)

12 Assign Objects to Variables x = 5 –store number 5 in computer memory –use variable x to refer to the number “=” is an assignment operator –Variable must be on the left and object must be on the right –Don’t confuse with the equal sign in math –The R language uses “  ” for assignment! If a variable is not assigned to an object –var x; //x is undefined A variable can refer to different objects –Type can change when different objects are assigned the variable Check variable type –Use built-in function typeof() to check variable type

13 Assign Objects to Variables An object can have no name, one, or more than one name associated with it Objects with no name associated with them are called literals 123, “abc”, false/true How to swap the objects of two variables? –x=3; y=4; An object can have more than one name associated with it –x=3; y=x

14 Variable Examples

15 Variable Example

16 Variables and Scopes Variable declaration in JavaScript –Do you have to declare a variable before use the variable? –What’s difference between a declared variable and an undeclared variable? –var x = 5 vs. x = 5 Example script in VariableScope.html Local and global variables

17 Statements Commands to the browser Assignments Function calls Object methods Statements starts with key (reserved) words –return, if … else, while, do … while, … Semicolon separates statements –If you want to write multiple statements on a line –Not necessary if each line has one statement

18 Objects A chunk of data with properties/attributes and methods Properties are the values associated with an object Methods are the actions an object can perform What’s the syntax difference between accessing a property and invoking an action Primitive objects (literals) –Objects that can have no names –numbers, strings –Don’t need to create them using the new key word

19 Primitive Objects (Literals) Objects that can have no names Numbers –3+4, 3*4 Methods –3.toString() –3.345.toFixed(2) –3.345.toPrecision(3) Special numbers –Infinity (-Infinity), NaN (not a number)

20 Primitive Objects (Literals) Strings –“abc”, “abc” + “efg” Properties & Methods –“abc”.length –“abc”.slice(1,2)

21 Array Objects Two ways of creating Array objects –numbers=[1,2,3]; –numbers=new Array(3); Properties & methods –What properties and methods you have been using? The length property –Properties don’t have parameters to access values The join method –Methods have parameters to control actions

22 The Math Object Basic math functions are provided as methods of the “Math” object in JavaScript –Math.floor(), Math.round(), … Not a usual object –You don’t need to create the object –There is only one Math object Equivalent to a module or library in other programming language

23 Functions What are functions? –A function is a named sequence of statements that performs a certain computational task –A block of code perform a certain task –Execute the block of code by referring to the name and providing arguments Does a function have to have input(s) and return object(s)? –It usually (but not necessarily) takes inputs –Every function returns object(s) –If you don’t put the return statement in a function, the return from the function is undefined Not built-in functions. All the functions are user-defined.

24 Write Functions Writing a function is also called function definition How to define (or write) a function in JavaScript? –Function head –Function body—curly bracket Write a function which raises a to the power of b –mypow(a,b) Functions must be defined before they can be used!

25 Function with Arguments/Parameters Parameters vs. Arguments –formal parameters vs. actual parameters Parameters are the names inside a function referring to the objects passed to the function –Function definition Arguments are the objects provided to a function when the function is called –Function use How are arguments passed to parameters (binding)? –Input objects/variables are passed to the parameters by their order/position –Doesn’t matter what names used by the arguments Arguments are evaluated before the binding –Power(1+1, 5-2) is the same as Power(2, 3)

26 Function Invocation FunctionName() When a certain event occurs – (figure 8.8 in Peterson’s book) Use a timer to invoke a function –setInterval() Functions are objects in JavaScript –Have properties and methods –call() & apply() methods –First parameter is the owner object Example –a=[3,2,1] –Math.min.apply(null, a)

27 Benefits of Writing Functions? Parameters provide abstraction –Code that manipulate not specific objects –Abstract calculation Reuse code –function code needs to be copied into different code –What happens if there are errors in the function code Create modular program –Divide a large program into functions (divide and conquer) –Vertically and horizontally Increase productivity –Several programmer can work on the same program

28 Recursive Functions Factorials –N!, N is a non-negative integer –The product of all positive integers less than or equal to n –The product of N and the factorial of (N-1) and 0!=1 Sum(a, b) calculates the sum of the integers from a to b where a and b are integers and a <=b RecursiveFunctions.html Peterson Figure 8.12 –8_11-time_to_event_recursion.html –Should use a timer instead of recursive function

29 Objects A complex variable with properties and methods Properties –Values associated with an object objectName.propertyName objectName[expression] Methods –Actions can be performed on an object objectName.methodName()

30 Objects Creating objects –Object literal –“new” key word –Object constructor A special function can be called by “new” “this” Creating an Array object Example –Objects.html Additional properties can be added –Same type of objects may have different number of properties

31

32 Objects Nested objects –Properties are objects Geography features (point, line, polygon) –Attributes and locations Additional properties can be added –Same type of objects may have different number of properties

33 Events Message/commands or actions an object can recognize and react –Invisible vs. visible objects Event handlers –reactions objects can perform when events happen Most HTML elements have events—also called DOM events –Mouse click, web loaded, … Example –Events.html


Download ppt "JavaScript Programming. What Is JavaScript “the most popular programming language in the world”— w3schools.com “the language for HTML, the Web, computers,"

Similar presentations


Ads by Google