Function Declarations:
function functionName(parameters) {
code to be executed
}
EXAMPLE:
<!DOCTYPE html> <html> <body> <p>This example calls a function which performs a calculation, and returns the result:</p> <p id="demo"></p> <script> function myFunction(a, b) { return a * b; } document.getElementById("demo").innerHTML = myFunction(4, 3); </script> </body> </html>
the result: 12
The Function() Constructor:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var myFunction = function (a, b) {return a * b} document.getElementById("demo").innerHTML = myFunction(4, 3); </script> </body> </html>
the result: 12
Self-Invoking Functions:
<!DOCTYPE html> <html> <body> <p>Functions can be invoked automatically without being called:</p> <p id="demo"></p> <script> (function () { document.getElementById("demo").innerHTML = "Hello! I called myself"; })(); </script> </body> </html>
the result: Hello! I called myself
Functions are Objects!!!
JavaScript Closures:
<!DOCTYPE html> <html> <body> <p>Counting with a local variable.</p> <button type="button" onclick="myFunction()">Count!</button> <p id="demo">0</p> <script> var add = (function () { var counter = 0; return function () {return counter += 1;} })(); function myFunction(){ document.getElementById("demo").innerHTML = add(); } </script> </body> </html>
every click the botton,the number will add one.