JavaScript Functions

  1. Declaration
    1. Defined with function
      function rectangleArea(width, height) {
      	return width * height;
      }
    2. Return value is optional
    3. Can be defined before or after function call
  2. Variable scope
    1. Local variables must be defined with var
      function sayHello() {
      	var name = "John";
      	alert("Hello, " + name);
      }
      
      sayHello();
      alert(name);   // ERROR! name is not defined 
      
    2. Missing var makes variable global
      function sayHello() {
      	name = "John";    // Global variable
      	alert("Hello, " + name);
      }
      
      sayHello();
      alert(name);   // John
      
    3. Global variables are actually attached to window object
      alert(window.name);   // John
      
    4. Best practice is to always declare every variable
  3. Optional and variable-length arguments
    1. Test to see if the parameter has been defined
      function sayHello(name) {
      	name = (typeof name === "undefined") ? "John" : name;	
      	alert("Hello, " + name);
      }
      
      sayHello("Bob");  // Hello, Bob
      sayHello();       // Hello, John
      
    2. Coming in ECMAScript 6
      // Only works in FireFox
      function sayHello(name = "John") {	
      	alert("Hello, " + name);
      }
      
    3. arguments property gives array-like access to parameters
      function add() {
      	var result = 0;
      	for (var i = 0; i < arguments.length; i++)
      		result += arguments[i];
      		
      	return result;
      }
      
      x = add(2, -1, 3);  // 4
      
      
  4. Anonymous functions
    1. Named functions may be assigned to a variable
      function sayHello() { alert('Hello'); }
      
      var x = sayHello;
      x();        // Hello
    2. Anonymous function can also be assigned
      var sayHelloAnonymous = function() { alert('Hello'); }
      sayHelloAnonymous();    // Hello
      
      var area = function(width, height) { return width * height; }
      x = area(2, 3);   // 6
    3. Anonymous function that executes immediately - Immediately Invoked Function Expression (IIFE)
      (function(name) { alert('Hello, ' + name); }('Bob'));
      
      // or
      (function(name) { alert('Hello, ' + name); })('Bob');
      
    4. Anonymous functions as function arguments
      // Register an event listener
      my button = document.getElementById('mybutton');
      button.addEventListener('click', function() { 
      	alert('Button was clicked'); 
      });
      
      // Loop through an array
      var nums = [2, 4, 6, 8];
      nums.forEach(function(element, index, array) {
      	console.log(index + ' = ' + element);
      });