Complex functions
Fun with Functions
Delving Deeper in to Functions
We've already seen a variety of functions, from built-in functions like console.log(), to a few of our own built using const functionName = function(){}. We've also already learned how to invoke or execute functions with (), as well as passing in a few simple arguments (like we've done with prompt("some string")). Let's dig into these a bit deeper.
a new syntax (part 1)
Up to this point, we've been writing functions like this:
const someFunction = function someFunction() {};While it's clear what's going on here, we have another way writing functions that's a bit cleaner. It's called a named functional expression, and it looks like this:
function someFunction() {}While there are some technical differences between the two ways of declaring functions, the latter is used much more widely than the former, and is generally a bit easier to read. As long as we treat the functional expression the same way we were treating it's const-based cousin, we should be fine (and save ourselves a few keystrokes in the process).
the return keyword
return keywordHere's a function that returns a value without any side effects:
function greeter() {
return "Hello";
}
// saving the return value
const greeting = greeter();
// using the return value to compose larger expressions
console.log(`${greeting}, nice to meet you.`);
// what's the difference here?
console.log(`${greeter()}, nice to meet you.`);The result of evaluating an expression consisting of a function reference followed by an invocation operator is the value to the right of the keyword return inside the function. Easy peasy, right?
Portfolio Project 1:
Refactor every instance of const someFunction = function() across your portfolio project into a named functional expression. Be sure to double-check that we haven't caused any regressions!
Arguments
During every function invocation, you have access to the arguments keyword, which contains all the inputs to the function invocation. Play with this concept until you're sure you understand it.
Exercise 1:
In your dev console, create a function
logAndReturnthatconsole.logs all of its inputs and thenreturns them. HINT:Store the
returnvalue as a variablereturnedValues. HINT:Pass that variable as an argument to a second invocation of
logAndReturn. HINT:
Parameters
It's unwieldy to work with the arguments keyword directly. Usually we use named parameters to give our inputs (arguments) variable names for the length of the function invocation
Exercise 3
Simple Math
Write a function called
triplerthat takes a number and returns triple the value. HINT:Create a function
multiplythat takes two numbers as inputs and returns their product. HINT:Create a function
dividethat takes two numbers as inputs and returns the result of dividing the first by the secondCreate a function
remainderthat takes two numbers as inputs and returns the result of modulo the first by the secondUsing only the functions you wrote above, and no operators, calculate the value of tripling 5, multiplying that by 12, dividing by 2 and then finding the remainder of dividing that by 3.
Portfolio Project 2
Functional Components
Our component library currently consists of four top-level components. So far, these have worked well for our landing page, but we don't yet have a way of using these components across different views. Let's change that by turning these components into more flexible functional components that return markup for us to use.
Let's start with the
Headercomponent, since that will almost always need to change in response to the current page. The first thing that we should do isexportafunctionthatreturns the original HTML string. Something like:...which we can use in our
index.jsfile with:We should try to think of our components as pure, "dumb" expressions of the state of our application. That application state could eventually get pretty complicated, so let's think of that state as an Object that can eventually store lots of data for us. Let's create that state Object in
index.js, then pass that state to our component. Inindex.js:...and in
Header.js:Let's turn every other component into a functional component to be invoked with a
stateargument (even if we don't actually respond to any part of that state just yet). By the time we're done, our application markup generator should look like:
To make this a bit more useful, we need to learn a bit more about how users can interact with our application through Events.
Events
An event handler is a function that is run when some pre-defined "event" occurs in the browser. Try to make the following work in the dev console while inspecting your Portfolio Project:
A new syntax (part 2)
When a function is used as a callback, it's often written inline as in the example above. These function traditionally don't have names of their own, and are instead referred to as anonymous functions.
As you see in the examples above, they can be fairly tedious to write out. To help with this (and with the binding of the this keyword, which we'll cover later), JavaScript has given us a new syntax for anonymous functions called "arrow" syntax. It looks like this:
Portfolio Project 3
See if you can add some click event listeners that log different page names to the console when a navigation bar link is clicked. HINT: be sure to add your event listeners after the innerHTML of the #root element has been set!
Last updated