Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
86 lines (59 sloc) 2.93 KB

LESSON: js-functions


2018-06-11

Tags: javascript, objects, functions

OBJECTIVES

  • Create and invoke functions that take an arbitrary number of arguments
  • Create and invoke functions that take reference types as arguments
  • Create and invoke functions that return reference types
  • Create and invoke functions that take functions as arguments
  • Create and invoke functions that return functions

VOCABULARY

Function: a block code that can be invoked at a later time, defined with the function keyword.

  • Functions can be defined in various ways:

  • Functions can be named so you can reference them later with the variable name:

  • let someFunc = function() {
    // code here
    }
  • or anonymous:

  • function() {
       // code that runs when function is
       // called is here
     }
    

Function body: the code contained within a function that runs when the function is invoked:

let someFunc = function() {
   // body is in here, between the 
   // curly braces
 }

Function Return value: the value returned from the function, that other parts of the program receive by invoking the function. When no return value is specified with the return keyword, undefined is returned. So, a function always returns something.

Function argument: the value(s) passed into a function that match up with the parameters that were specified when the function was defined

Function Parameter: The named local variables that a function can receive when invoked. These are defined when the function is defined within the parentheses:

let someFunc = function (param1, param2, etc) { … }
  • If you do not define any parameters, then the function cannot receive any named values when invoked. The arguments variable is always set up as an array of incoming arguments when a function is invoked.

Callback: A callback is a function that is passed to another function.

let funcWithCallback = function(num1, num2, operation) {
	operation(num1, num2) 
    // operation is another function that will be 
    // passed into funcWithCallback as an argument. 
    // Whatever functions is passed in as the 3rd 
    // argument is a callback function. It could be 
    // something like add(), subtract(), multiply(), 
    // etc.
}

NOTES

  • Order and type of arguments are important
  • It is up to the developer to know the order and type of arguments a function is expecting.
  • You must call the function with the correct order and type of argument that the function expects to receive. That is, when you define the function, you specify an order and kind of parameter that will be used in the function body. So when you invoke it, you need to pass in the correct order and type of argument.
  • Functions can return primitives or reference types
    • Reference types are useful to return when you need to return multiple things

EXAMPLES