CS346 Javascript-41 Module 4 JavaScript Functions
CS346 Javascript-42 Functions Function — allows you to treat a related group of statements as a single unit The syntax for defining a function is: function nameOfFunction (parameters) { statements; }
CS346 Javascript-43 Returning Values A return statement ensures that a function returns a specific value to the main script This is done using the return keyword You are not required to return a value from a function When a function performs a calculation it normally wants to receive a return value There is no void/type for the return value
CS346 Javascript-44 Function Example Function #1 Example <!-- Hide var message = "I came from a function defined in head!"; function prnMsg() { document.write(message); } // Unhide -->
CS346 Javascript-45 Function Return Example Function #3 Example - Returning A Value <!-- Hide function getAvg(num1,num2,num3) { var avgResult = (num1+num2+num3)/3; return(avgResult); } // UnHide -->
CS346 Javascript-46 Naming Functions Functions in JavaScript are case sensitive Must begin with a letter or an underscore character Cannot begin with a number Cannot contain any embedded spaces Function names should reflect their purpose
CS346 Javascript-47 Examples JS-4 Examples 4-1function.htm 4-2function.htm 4-3function.htm 4-4function.html