JavaScript Functions
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!
Output Black Box Inputs
Different Types of Functions Who writes? JavaScript provides Someone else writes & you use You write Frist two today
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
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
Return Parameters Function
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
Functions as Statements Performs an action but doesn’t give you anything back Example: alert
Alert String to print Function
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
Using eval formname.fieldname.value = eval(‘3+5’); alert(eval(formname.inputfield.value));
Format of a Function functionName(parm,parm); Always needs () even if no parameter functionName();
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
JavaScript Functions
alert Takes an input value (string) Does not return a value
Getting a random number Math.random() Does not need any inputs Returns a value between 0 and 1
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)
eval Takes an input value (string) Returns a value (number)
Connecting JavaScript to HTML
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
A Separate JavaScript File <script src="myscripts.js"></script> Myscript.js JavaScript option in komodo will work on it next
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)