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 that does not return a value (like C++ void function)
      function sayHello(name) {
      	document.writeln("Hello, " + name);
      }
      
    4. Function that returns a value
      function max(x, y) {
      	if (x < y)
      		return y;
      	else
      		return x;
      }
      
  2. Scoping
    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)
    3. Example:
      let x = 3;
      
      function test() {
      	// y is local
      	let y = 10;
      	document.writeln("y is " + y);
      	
      	// x is global
      	document.writeln("x is " + x);
      }
      
    4. 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
      
    5. Built-in functions
      1. Global functions (sample)
        1. parseFloat("s") - Converts the beginning of a string to a floating-point value; returns NaN if unsuccessful
          let x = parseFloat("1.23");   // 1.23
          
        2. parseInt("s") - Converts the beginning of a string to an integer value; returns NaN if unsuccessful
          let x = parseInt("66");   // 66
          
        3. isNaN("s") - Returns true if the argument is not a number, false otherwise
          if (isNaN("dog")) {
          	console.log("'dog' is not a number.");
          }
          
          // Careful... empty string or string with all spaces is NOT NaN!
          if (!isNaN("")) {
              console.log("Empty string is a number!");
          }
          
        4. isFinite(value) - Returns true if the argument is a number in the range that JavaScript supports, false otherwise
          isFinite(123)           // true
          isFinite(6.5)           // true
          isFinite(false)         // true (because false = 0)
          isFinite("dog")         // false
          
      2. Dialog boxes
        1. alert(s) - Alert dialog box with OK button

          alert dialog box
          alert("This is an alert.");
          
        2. prompt(s) - Dialog box that prompts the user for a single line of text; returns the text or null if Cancel is pressed

          prompt dialog box
          let firstName = prompt("Enter your name:");
          
        3. confirm(s) - Dialog box that asks a question; returns true if OK is pressed, false otherwise

          confirm dialog box
          let answer = confirm("Are you sure?");
          
    6. 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);
        });
        
    7. Arrow functions (introduced in ES6)
      1. arrow functions are a replacement for wordy anonymous functions
      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);
        });