Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Functions.

Similar presentations


Presentation on theme: "JavaScript Functions."— Presentation transcript:

1 JavaScript Functions

2 What is a function? Collection of statements that can be invoked as a unit Because sometimes we want to do more that a single assignment!

3 Output Black Box Inputs

4 Different Types of Functions
Who writes? JavaScript provides Someone else writes & you use You write Frist two today

5 Does function need information?
Alert does…tell it what to write Asking for a random number doesn’t Always need to use () Parameters if data needed () if not

6 Parameters Call a function with a different value every time
MUST give it everything that it expects For alert One parameter, the string to print

7 Return Parameters Function

8 Statement or part of an expression
Alert is a statement; doesn’t give you anything back If you ask for a random number, you expect to get something back

9 Functions as Statements
Performs an action but doesn’t give you anything back Example: alert

10 Alert String to print Function

11 But What if I Want a Value Back?
For calculator: eval(string) Like alert, takes a string as a parameter Does its magic on the string And gives you back a number You can do what you want with the number Put it in an alert Write it out to a form Do more math on it

12 Using eval formname.fieldname.value = eval(‘3+5’); alert(eval(formname.inputfield.value));

13 Format of a Function functionName(parm,parm);
Always needs () even if no parameter functionName();

14 The rules The order of the parameters matter Only a single output
5 - 3 different than 3 -5 Any number of parameters can be defined Fixed for any specific function Only a single output Optional in general But always the same for any specific function More common model

15 JavaScript Functions

16 alert Takes an input value (string) Does not return a value

17 Getting a random number
Math.random() Does not need any inputs Returns a value between 0 and 1

18 Other math functions Take an input value (number)
Math.round(num) Math.floor(num) Math.ceil(num) Take an input value (number) Return a value (number)

19 eval Takes an input value (string) Returns a value (number)

20 Connecting JavaScript to HTML

21 Where Do JavaScript Functions Go?
Like CSS, can be inline or a separate file Like CSS, an external file is considered better practice Like CSS, link to it from the head section

22 A Separate JavaScript File
<script src="myscripts.js"></script> Myscript.js JavaScript option in komodo will work on it next

23 FUNCTION: connecting to HTML
<head> <script src=“function.js”></script> </head> <body> <button type=“button” onclick=“doit();”> </body> HTML file name function name function doit () { alert(“Hi!”); } JAVASCRIPT (function.js)


Download ppt "JavaScript Functions."

Similar presentations


Ads by Google