Functions - A First Look

Objectives

  1. Be able to articulate what a function is and how they are used
  2. Describe in your own words why you write functions
  3. Write and use a simple function that takes arguments and returns a value

Terms

  • function
  • parameter
  • argument
  • return value
  • invoke

What are functions?

A set of statements that perform a task or calculate a value

1
1

Declaring a Function

function getHello() {
    // return the word Hello
    return "Hello";
}

getHello();
//Hello
function keyword
name
body

Declaring a Function

function formatMessage(recipient,msg) {
    // print the message to the console
    return recipient + ' You have a message:\n ' + msg;
}

formatMessage("John", "Your appointment is at 6pm");

//John You have a message:
// Your appointment is at 6pm
function keyword
name
body
parameters

Example

Write a function that returns the sum of two numbers

Exercise 1

Write a function that multiplies two numbers

Exercise 2

Write a function that adds two numbers then multiplies that result by a third number

Wrap Up

Functions are sequences of instructions that perform a specific task

Functions can be defined with parameters

Functions may return values

The values passed to function when it's invoked are called arguments

Made with Slides.com