1 of 10

JAVASCRIPT

06: FUNCTIONS

What are functions and their headers, calls, parameters, and returns?

2 of 10

WHAT IS A FUNCTION

  • Block of code designed to perform particular task
  • Function is executed when the function is called
  • Makes code more efficient and readable
    • Can put code into a function and then call that function each time you need to run that code instead of simply repeating it

3 of 10

FUNCTION HEADER

function square(num) {

return num * num;

}

  • Used to declare a new function
  • First line of a function is the function header
  • Used to declare a new function
  • In the format function keyword, name, (parameters)

function name(parameter1, parameter2, parameter3) {

// code to be executed

}

Header

4 of 10

CALLING A FUNCTION

  • Put the function keyword, function name, and parentheses
  • Put the values you want to pass into the function between the parentheses (as parameters)
  • Make sure the number of values you put in matches the number of parameters in the header

function toCelsius(fahrenheit) {

return (5/9) * (fahrenheit-32);

}

let value = toCelsius(77); // function calling

value = (5/9) * (77-32);

5 of 10

WHAT IS A PARAMETER

  • Variable passed into a function
  • Put the name of the parameter in between
    • Type is not necessary for JavaScript
  • Parameters are separated by commas
  • Can put as many as you want
  • Terminology:
    • Parameters are listed inside the parentheses () in the function definition
    • Function arguments are the actual values a function receives when it is called

CREDITS: This presentation template was created by Slidesgo, and includes icons by Flaticon, and infographics & images by Freepik

6 of 10

WHAT IS AN ARGUMENT

function toCelsius(fahrenheit) {

return (5/9) * (fahrenheit-32);

}

let value = toCelsius(77);

  • A value passed to a function when the function is called
  • Different from parameter
    • Parameter is the variable
    • Argument is the value
  • Also called actual parameter

Parameter

Argument

7 of 10

FUNCTION RETURN

  • Function will stop executing when the return statement is reached
  • Return value can be “caught” with a variable or used like a variable

// Function is called, the return value will end up in x

let x = myFunction(4, 3);

function myFunction(a, b) {

// Function returns the product of a and b

return a * b;

}

8 of 10

TRY IT YOURSELF

Go to onecompiler.com/javascript

Create a function that concatenates strings, try calling it, and see what else you can do!

9 of 10

FUNCTIONS REVIEW

Go to gimkit.com/join

10 of 10

THANKS!

Any questions?

codingpower101@gmail.com

codingpower.org