Introduction

In this part, we will look at the following topics:

  • Function arguments.
  • Returning values from functions, together with a practical example.
  • Creating HTML inside a function from the values inside an array.

Function arguments

Function arguments are values that get passed into functions.

Technically, in function declarations, the variables are called parameters.

In the code below, name is the parameter. It’s up to you, the developer, to decide what to call the parameter. It’s called ‘name’ here, but this is only one example. Giving function parameters descriptive names that reflect the expected data category or data type is a good idea.

function printName(name) {
  console.log(name);
}

When we call the function using parenthesis, the value passed into the function parameter is called an argument.

printName("Sofie");

What we pass in the parenthesis becomes the value of the name in the function. In this case, name will receive the value “Sofie”.

So, the console log inside the function will display Sofie in the console.

We want to pass different values into a function so that the code inside can perform the same actions on different values (data).

Function arguments

This Scrimba takes a further look at function arguments.

Returning values from functions

We can return a value from a function, and we can assign that return value to a variable.

We look at how to do that in this Scrimba.

A function return value example

Below is an example of using the return value of a function.

In this Scrimba, a simple age-checking function for a website is created.

Creating HTML in a function

A common task you will perform when fetching data from APIs is how to use functions to create HTML with the values inside an array.

In this Scrimba:

  • An array is passed into a function as an argument.
  • An HTML string is created inside the function from items in the array.
  • The string is returned from the function and assigned to a variable.
  • The variable is assigned to the innerHTML property of an existing HTML element.

Activities

WATCH

The below tutorial video on HTML in Loops (1h 51m).


Lesson Task

Brief

There are practice questions in the master branch of this repo.

Attempt to answer the questions before checking them against the answers in the answer branch of the repo.

Tags: