JavaScript Functions

  1. Overview
    1. Functions may be defined before or after a call to the function
    2. Function parameters are always passed by value
    3. Function with no return statement returns undefined
      function sayHello(name) {
      	console.log("Hello, " + name);
      }
      
    4. Function that returns a value
      function max(x, y) {
      	if (x < y) {
      		return y;
      	}
      	else {
      		return x;
      	}
      }
      
    5. Default parameter values
      // z is 0 if not supplied
      function sum(x, y, z = 0) {	
      	return x + y + z;
      }
      
      total = sum(1, 2);     // 3
      total = sum(1, 2, 4);  // 7
      
  2. Variable scope
    1. Local variables are scoped to the function they are declared in (only accessible within the function)
    2. Global variables are declared outside a function and have global scope (accessible anywhere)
      // x is global
      let x = 3;
      
      function test() {
      	// y is local
      	let y = 10;
      	console.log("y is " + y);
      	
      	// x is global
      	console.log("x is " + x);
      }
      
    3. Variable declared with let has block scope, but variable declared with var does not
      function test(num) {
      	if (num > 0) {
      	   let x = 2;
      	   console.log("x is " + x);
      	}
      	
      	// Exception thrown because x is scoped to the if statement 
      	console.log("x is " + x);
      }
      
    4. Variable declared with var does not have block scope
      function test(num) {
      	if (num > 0) {
      	   var x = 2;
      	   console.log("x is " + x);
      	}
      	
      	// No exception thrown because x is scoped to the function 
      	console.log("x is " + x);
      }
      
    5. Warning: Implicitly declared variables (no let or var) have global scope!
      function test(num) {
      	if (num > 0) {
      	   // Implicitly declared
      	   x = 2;
      	   console.log("x is " + x);
      	}	
      }
      
      test(2);
      
      // No exception thrown because x is global  
      console.log("x is " + x);
      
    6. Warning: Global variables declared with var or implicitly declared become properties of the global object
      // Adds x as a property to window
      var x = 5;
      
      // Adds y as a property to window
      y = 10;
      
      // Does NOT add a property to window 
      let z = 20;
      
      console.log(window.x);  // 5
      console.log(window.y);  // 10
      console.log(window.z);  // undefined
      
  3. Inner and outer functions
    1. An inner function (nested function) is a function declared inside another function
    2. An outer function is a function containing an inner function
    3. An inner function can access variables declared in the outer function
      function outerFunc() {
         let value = "Test";
         function innerFunc() {
            console.log(value);
         }
         innerFunc();
      }
      
      outerFunc();  // Outputs "Test"
      
    4. Example that filters out odd numbers from an array
      function getEventNums(nums) {
         function isEven(num) {
            return num % 2 === 0;
         }
         
         return nums.filter(isEven);
      }
      
      let nums = [8, 3, 2, 5];
      let evens = getEventNums(nums);  // returns [8, 2]
      
      
  4. Anonymous functions
    1. An anonymous function is a function that doesn't have a name
      // Assign an anonymous function to a variable
      let hello = function() { alert('Hello'); }
      
      // Variable acts like a function
      hello();
      
    2. Pass anonymous functions to functions expecting function references
      let nums = [8, 2, -1, 5];
      
      // Sort in descending order
      nums.sort(function(a, b) {
          return b - a;
      });
      
      // Display the even numbers in the array
      nums.forEach(function(n) {
      	if (n % 2 == 0)
      		console.log(n);
      });
      
  5. Arrow functions (introduced in ES6)
    1. An arrow function is a replacement for a wordy anonymous function
    2. Basic syntax
      (param1, param2, …, paramN) => { statements }  // No return value
      (param1, param2, …, paramN) => expression      // same as: => { return exp; }
      
      // Parentheses are optional when there's only one parameter:
      (singleParam) => { statements }
      singleParam => { statements }
      
    3. Example arrow function that doesn't return a value
      let hello = name => console.log("Hello, " + name);
      hello("Bob"); 
      
      // Same as
      let hello = function(name) {
         console.log("Hello, " + name);
      };
      
    4. Example arrow functions that return values
      let add = () => 1 + 2;
      let num = add();  // 3
      
      // Same as
      let add = function() {
      	return 1 + 2;
      };
      
      let subtract = (x, y) => x - y;
      let num = subtract(4, 3);   // 1
      
      // Same as
      let subtract = function(x, y) {
         return x - y;
      };
      
    5. Use anytime you need an anonymous function
      let nums = [8, 2, -1, 5];
      
      // Sort in descending order
      nums.sort((a, b) => b - a);
      
      // Display the even numbers in the array
      nums.forEach(n => {
         if (n % 2 == 0) {
            console.log(n);
         }
      });