Javascript Functions

  • let us wrap bits of code in REUSABLE packages; building blocks

Declaring and Calling Functions

  • function declaration (definition):
    function functionName(argument){                             // argument is optional
        // run some code
        return infoNeeded;                                       // return is optional
    }
  • example
    function doSomething(){
      console.log("Hello World");   // run some code
    }
    • function names start lowercase and use camelcase
  • call function (use it):
    doSomething();
    doSomething();
    doSomething();
    doSomething();
  • in the console, if you type the name of the function without parenthesis it will print out the function declaration
  • to clear the console use the function clear()

Arguments

  • optional --- can have none
  • inputs to the function
  • separated by commas
  • arity is the number of arguments
  • in JS, you can leave out an expected argument without your code breaking, it will just print undefined where that argument was supposed to be (this is because it's 'loosely typed')

Return Keyword

  • returns an output from a function that can be used outside the function
  • can be optional --- function may just do something while being executed and nothing in it is needed to be saved for anything --- not assigned to a variable
  • only one return statement will run for each call of a function --- first one encountered --- stops execution of the function when hits return statement
  • all JS functions return something --- it will return undefined if we don't explicitly tell it to return something

Function Declaration, Function Expression, Arrow Functions

Function Declaration

  • function declaration:
    function functionName(argument){                             
        // run some code
        return infoNeeded;                                      
    }
  • visible outside it's scope

Function Expressions

  • assigns the return to a variable or self-invokes the function
    • anonymous:
      let variableName = function(argument){                   
          // run some code
          return infoNeeded;               
      }
      • call the function with variableName()
    • named:
      let variableName = function functionName(argument){     
          return infoNeeded;               
      }
      • functionName is not visible outside it's scope (unlike function declaration)
    • self invoking:
      (function functionName(argument){    // functionName is optional --- can be anonymous
          // run some code
          return infoNeeded;               // return optional                 
      })(argument);
      • a good use of a self invoked function is for variable scoping
      • if it has a return value, it can be used as a parameter to another function
    • if you overwrite variableName later in the program then the original function is gone

Arrow Functions

  • single line: const variableName = parameter => something simple done with parameter
    • example const calcAge = birthYear => 2037 - birthYear;
      • it is also a function expression, just more condensed
      • return is implicit
  • if need multiple lines, then open curly braces:
   const yearsUntilRetirement = birthYear => {
       const age = 2037 - birthYear;
       const retirement = 65 - age;
       return retirement;
   }

or

   const yearsUntilRetirement = (birthYear, firstName) => {
       const age = 2037 - birthYear;
       const retirement = 65 - age;
       return `${firstName} retires in ${retirement} years.`;
   }
  • need parenthesis if there is more than one parameter
  • return is no longer implicit

Should We Always USe Arrow Functions? ... No

  • arrow functions do not get a this keyword

Higher Order Functions

  • functions that either take a function as an argument, or they return a function
  • example:
    function sing(){
      console.log('twinkle twinkle...');
      console.log('how i wonder...');
    }
    setInterval(sing, 1000);   // runs the function every 1000 milliseconds(1 second)
    • sing doesn't need parenthesis as an argument because we're not calling it, we're just telling setInterval which function to call
    • setInterval prints a number when you call it --- this number is passed to clearInterval () when you want to stop setInterval from running
  • can pass anonymous functions
    • format:
      higherOrderFunctionName(function(){
          // anonymous function code
      }, optionalAdditionalArguments)
    • anonymous function can't be called outside the higher order function it is declared in

Copyright © 2022