Skip to content

SEIR-7-06/functions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 

Repository files navigation

Lesson objectives

After this lesson students will be able to:

  • Define a function
  • Understand function parameters and arguments
  • Define a function with a return value
  • Combine functions with conditionals and loops

FUNCTIONS

WHAT IS A FUNCTION?

Functions are a powerful construct in programming that allow us to organize our programs into chunks. We can think of a function like a black box that take in some input and returns an output.

Function-Machine



Say for example, we wanted a function that would tell us the first item on our grocery list. We could create a function that would take a grocery list as its input and return the first item on the list as its output.

Get-first-item



DEFINING A FUNCTION

Let's start with the basic structure of a function.

To define a function we include the function keyword followed by the function name, a set of parentheses and then the body of the function.

function func() {
  console.log('This will be called later');
}

This code by itself will not run. To run this code we can call or invoke the function like so.

func();

To call the function simply include the name of the function followed by a set of openning and closing parentheses.



WHY FUNCTIONS?

Functions give the ability to organize our code into chunks and give those chunks names. This makes the code easier to understand and to reason about.

Functions allow us to store a line of code for later to be used as many times as we wish. This saves us from having to rewrite the same code many times. It follows the DRY principle (Don't Repeat Yourself).



CALLING A FUNCTION MANY TIMES

A function can be called many times and in this case will give us the same output every time.

function logAlert() {
  console.log('Ah ah ah... you didn\'t say the magic word.');
}

logAlert();
logAlert();
logAlert();
logAlert();
logAlert();


Practice defining your own function that logs out a message. And then call that function as many times as you want.



PARAMETERS

Functions can take in information and then act on that information in the form of parameters.

In this case the printGreeting function takes in a name parameter and prints out a custom message with the name inserted.

function printGreeting(name) {
  console.log(`Welcome ${name}`);
}

const firstName = 'Jane';

printGreeting(firstName);

When calling printGreeting(firstName) the value we pass to it is refered to as an argument. When defining the function the values pass in are refered to as parameters.



PASSING MULTIPLE PARAMETERS

We have the ability to pass many parameters to a function.

We've set up this function to take in 3 parameters and print out a longer greeting with the three values inserted.

function printLongGreeting(name, numberOfMessages, dayOfWeek) {
  console.log(`Welcome ${name}. Today is ${dayOfWeek}. You have ${numberOfMessages} messages.`);
}

printLongGreeting('Sam', 12, 'Friday');

Often we will pass variables as the arguments to the function when we call it.

const userName = 'Roberta';
const usersMessages = 30;
const currentDayOfWeek = 'Thursday';

printLongGreeting(userName, usersMessages, currentDayOfWeek);


EXERCISE

Write a function that will log out a person's order at a restuarant, that takes in three parameters, the person's name, a menu item, and their table number. Then try calling the function passing it arguments.

Solution:
function printOrder(orderName, menuItem, tableNumber) {
  console.log(`${menuItem} for ${orderName} at table #${tableNumber}`);
}

printOrder('spaghetti', 'Jane', 5);


RETURNING A VALUE

A function can also return a value. This function takes in 2 numbers and returns the sum of those numbers.

function getTheSum(a, b) {
  return a + b;
}

const totalApples = 20;
const totalBananas = 10;

// Simply calling the function will not do anything in this case.
getTheSum(totalApples, totalBananas);

// Instead, that return value can be stored in a variable for later use, like so.
const sum = getTheSum(totalApples, totalBananas);

console.log(sum);


MORE PRACTICE WITH RETURN

This function takes in 3 pieces of information, the itemName, the price, and the mustGoByDate, and prints out a message using those 3 pieces of information.

function returnAdMessage(itemName, price, mustGoByDate) {
  return `I am selling ${itemName} for ${price}. It must go by ${mustGoByDate}.`;
}

const item = 'Lamp';
const price = 50;
const date = 'tomorrow';

const message = returnAdMessage(item, price, date);

console.log(message);

The function returns a value. We can store this return value in a variable and then log out the variable.

This function takes in 3 pieces of information, breakfastItem, currentDayOfWeek and the rating and returns a message using those 3 pieces of information.

function printBreakfast(breakfastItem, day, rating) {
  return `Today is ${day}. I ate ${breakfastItem}. I give a ${rating} out of 10`;
}

const todayBreakfast = 'Omelet';
const today = 'Monday';
const breakfastRating = 6;

const message = getMessage(todayBreakfast, today, breakfastRating);

console.log(message);


FUNCTIONS WITHOUT RETURN

If you leave out the return value in a function it will return undefined.

Take one of our earlier examples.

function printGreeting(name) {
  console.log(`Welcome ${name}`);
}

Here we are logging out a value but we are not returning anything.

Let's try to store the return value in a variable and then log out that variable.

const greeting = printGreeting('Sally');

console.log(greeting);

Under the hood our function actually looks like this.

function printGreeting(name) {
  console.log(`Welcome ${name}`);
  return undefined;
}


RETURN EXITS THE FUNCTION

A return statement will exit the function, meaning nothing under the return statement will run.

Take for example our example that takes in a first name and a last name and returns the full name.

function getFullName(firstName, lastName) {
  return `${firstName} ${lastName}`;

  console.log('After the return.');
}

const fullName = getFullName('Fran', 'Babbage');

console.log('After calling the function.');

We will never see the After the return in our console. The function will return a value and exit the function before it even gets to that line of code.

Create your own example and try this out for yourself.



CONDITIONALS WITH FUNCTIONS

This function returns a message based on if the value passed in (hasFood) is true or false.

const hasFoodInFridge = false;

function getFoodMessage(hasFood) {
  if (hasFood) {
    return 'You are good to go';
  } else {
    return 'Time to get some groceries';
  }
}

const foodMessage = getFoodMessage(hasFoodInFridge);

console.log(foodMessage);

Because the function returns a value, in order to get access to the value we store it in a variable with...

const foodMessage = getFoodMessage(hasFoodInFridge);

After that we can log out the variable.



MORE CONDITIONALS WITH FUNCTIONS

This function will return a message based on if isAdmin and isLoggedIn is true.

function getLoginMessage(isAdmin, isLoggedIn) {
  if (isLoggedIn && isAdmin) {
    return 'Welcome admin user.';

  } else if (isLoggedIn && !isAdmin) {
    return 'Welcome website user.';
    
  } else {
    return 'You are not logged in.';

  }
}

const loginMessage = getLoginMessage(false);
console.log(loginMessage);

Hopefully we are starting to see how we can use functions to our advantage here. We can think of functions like a black box that take in some input and return an output. When we call our function we need to know about all the details happening inside. When calling the function we are just concerned with the information we give it, the parameters and the value that is outputed, the return value.

Here is the visual again

Function-Machine



BREIF REVIEW ON FOR LOOPS

Here we loop through each student in the list and log them out.

const students = [
  'Shawna',
  'Sam',
  'Sri',
  'Simone'
];

for (let i = 0; i < students.length; i++) {
  console.log(students[i]);
}


COMBINING LOOPS WITH FUNCTIONS

This function will loop through the list that is provided and if it finds an item that matches itemToCheck it will return true. If the itemToCheck is not found in the list, the function will return false.

const groceryList = [
  'spanich',
  'beans',
  'eggs',
  'watermelon',
  'blueberries',
];

function listHasItem(list, itemToCheck) {
  for (let i = 0; i < list.length; i++) {
    if (list[i] === itemToCheck) {
      return true;
    }
  }

  return false;
}

const hasItem = listHasItem(groceryList, 'soup');

console.log(hasItem);

This function will loop through a list and return a formatted version of the list turned into a string.

function getGroceryList(list) {
  let stringResult = '';

  for (let i = 0; i < list.length; i++) {
    stringResult += `${i + 1}. ${list[i]}\n`;
  }

  return stringResult;
}

const coolGroceryList = getGroceryList(groceryList);

console.log(coolGroceryList);


FUNCTIONS AND ARRAYS

We learned that arrays are a very handy way of storing related data. Let's take a look at combining them with functions.

ACTIVITY 1

Write a function that takes in an array of grocery items as a parameter and returns just the first item in that list.

Solution:
function getFirstItem(groceryList) {
  return groceryList[0];
}

const myList = ['spinach', 'tomato sauce', 'pickles'];

const firstItem = getFirstItem(myList);

console.log(firstItem);

ACTIVITY 2

This time write a function that will take in an array of grocery items and return the array with the first item removed.

For example, our function should take this as a parameter

const myList = ['spinach', 'tomato sauce', 'pickles'];

and return this.

['tomato sauce', 'pickles'];

Do some research to see how you can remove the first item from an array.

Hint: Google javascript remove first item from array.

Solution:

Eventually you may come across the shift method with JavaScript.

Read the documentation take a moment to see if you can understand how it's working.

function removeFirstItem(groceryList) {
  groceryList.shift();

  return groceryList;
}

const myList = ['spinach', 'tomato sauce', 'pickles'];

const updatedList = removeFirstItem(myList);

console.log(updatedList);

ACTIVITY 3

Write a function that takes an array of grocery items as its first parameter and a grocery item as its second parameter. This function should return true or false indicating whether or not the array includes the item.

Calling the function would look like this.

const hasItem = doesListHaveItem(myGroceryList, item);

Do some research to see how to check if an array includes an item.

Hint: Google javascript check if array has a particular item.

Solution:

After googling you might eventually come across the .includes method with JavaScript.

Read the documentation take a moment to see if you can understand how it's working.

function doesListHaveItem(groceryList, itemToCheck) {
  return groceryList.includes(itemToCheck);
}

const myList = ['spinach', 'tomato sauce', 'pickles'];

const hasItem = doesListHaveItem(myList, 'cookies');

console.log(hasItem);


FUNCTION EXPRESSIONS

A function expression is another way to define a function. Here we define a function without a name and store it in a variable.

const newFunction = function() {
  console.log('newFunction was called!');
}

newFunction();

Defining a function without a name, as we do on the right hand side of the equal sign is referred to as defining an anonymous function.



ARROW FUNCTIONS

A newer version of JavaScript (ES6 / ES2015) allows us to write a function with the following syntax.

const anotherFunction = (name) => {
  console.log(`Hey ${name}, anotherFunction was called!`);
}

anotherFunction('Lenny'); 

EXTRA STUFF TO TRY OUT

String and array methods

A method can be chained to a variable to perform an action. Example:

const message = "hello there";

console.log(message.toUpperCase());

=> "HELLO THERE"

.toUpperCase() is a method.


Datatypes

There are different methods for different datatypes.

Strings have different methods than arrays. In general, you can't use array methods on strings and vice versa.

Example of an array method:

const letters = ['A', 'B', 'C', 'D'];

console.log(letters.join(''));

=> ABCD

.join() is a method, but it is only for arrays.

It will not work on a string:

const letters = "ABCD";

console.log(letters.join(''));

Here, letters.join is not a function because .join is not a method you can use on strings. See: TypeError

.length is a method you can use on both strings and arrays


Methods can change the datatype

If we use .join('') on an array as intended:

const letters = ['A', 'B', 'C', 'D'];

console.log(letters.join(''));

It will however output a string. Be mindful of this when it comes to chaining methods.

For example .reverse() is an array method.

console.log(letters.join.reverse());

It will not work because the result of letters.join('') is a string.


Chaining built-in methods

You can chain methods together:

const str = "doodly doo";

console.log(str.split('').length);

=> 10

Be mindful of datatypes

This will not work:

const str = "doodly doo";

console.log(str.split('').toUpperCase);

πŸ”΅ Why Not?

Notice the error says TypeError. This is a big indicator as to what the problem is.

We are trying to use .toUpperCase() on the wrong type of data. In this case, we are trying to use it on an array, when it is not an array method. It is a string method.

πŸ”΅ Activity

RESEARCH

How can you reverse a string?

  • Try to use .reverse() on a string. Does it work?

  • If it does not work, what is the error telling you?

  • Try to use .reverse() on an array instead. Does it work?

There is no .reverse() method for strings, but there is one for arrays.

πŸ”΅ Activity

Using method chaining, figure out how to turn a string into an array, reverse the array, and turn the reversed array back into a string. This is one way to reverse a string. Chain the methods together on one line.

Some string methods

Some array methods


πŸ”΅ Extra

Look into regular expressions and the .match() method. Use .match() only to select parts of a reversed string that match a pattern.

πŸ”΅ Extra

Start in on this regular expressions exercise.



About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •