Function Basics

James Gibson

Objectives

  • Describe why a function is useful

  • Label the syntax of a function

  • Declare and invoke a function

  • Use the keyword return

What is a function?

A reusable sequence of instructions that achieve a specific task

Example usage of a function:

  • Calculating change (payment - total = change)
  • Converting text (SHOUTING)
  • Given a word, calculate it's scrabble score
  • Given a year, determine if it is a leap year

Why do we use functions?

Reproducable

const hello = (name) => {
    console.log(`Hello, ${name}`);
};

hello('James') 

"Hello, James"

Recap

Talk to your neighbor

In your own words, describe the purpose of a function

 

Give an example of a task to use a function for

Questions?

Syntax of a function

const hello = () => {
    console.log('Hello World');
};

Arrow Syntax

Your instructions go here.

Parens

Function name

^

ES6

Syntax of a function

function multiply(a, b) {
    return a * b;
};

Parameters 

return keyword

^

ES5

function keyword

Name

Syntax of a function

multiply(3, 4)


// 12

Arguments

Invoking a function

Function name

How the returned or logged information is shown in documentation

Recap Function Syntax

const multiply = (a, b) => {
    return a * b;
};

Identify and label each part of the function

Name

Parameters

Arrow Syntax

return keyword

Create and Invoke

Let's go code some stuff!

return keyword

const sum = (a, b) => {
    return a + b;
};

sum(5,3) // 8
const multiply = (a, b) => {
    return a * b;
};

multiply(2, 3) // 6

return keyword

const arrayLength = (array) => {
    return array.length;
};

arrayLength([1,2,3]) // 3

Define and invoke a function named "arrayLength" that accepts an array as its argument and returns the length of that array.

Recap

const division = (a, b) => {
    return a / b;
};

division(6, 3) // 2

What is a function?

What part of a function is this?

Describe this line

Why do we use "return"?

Made with Slides.com