What are Functions?

"Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects."

- excerpt from MDN docs. Click here to read more


Functions:
Quick
Overview
  • A function is a subprogram created to perform a certain task
  • To execute a function it has to be called. This is referred to as invoking a function
  • Values can be passed into functions and used within
  • Functions will always return a value. In JS, if there is no specific return value specified, "undefined" will be returned
  • Functions are objects
parts of a function
Defining a Function

Click the buttons to see the different ways to define a function

Calling a Function
  • When a function is defined, it doesn't automatically run. It has to be called(invoked)
  • You call a function by typing its name followed by parenthesis
  • The code inside the function body (between the curly brackets) will run (execute)
comments code
                    snippet
Parameters
  • inputs that a function can accept and then perform tasks with
  • they are placeholders for information that will be passed in when the function is called
  • parameter names are created when defining a function
  • multiple parameters must be separated by a comma
comments code
                    snippet
comments code
                    snippet
Arguments
  • Values that are passed to the function when it is called
  • can be passed to the funciton as values or as variables
comments code
                    snippet
Return
Statement
  • Functions always return a value.
  • If there is no return value specified, "undefined" will be returned.
  • when a return statement is used, the execution of the function is stopped. Any code after the return statement will not be executed
comments code
                    snippet
Immediately Invoked Function Expression

Immediately Invoked Function Expression
( IIFE )

  • A function that is called immediately after it is defined
  • The function expression is wrapped in brackets
  • The function is called by a pair of brackets added to the end of the function
  • Will typically be anonymous as it is only run once
  • will not be added to the global object
comments code
                    snippet