LogoLogo
  • FAC Curriculum
  • archive
    • Node & npm introduction
    • developer
      • Programming Paradigms
    • handbook
      • Asking for help
      • Coaching groups
      • Code review
      • Course rules
      • Debugging
      • Employment schedule and material delivered in FAC20
      • GitHub Workflow
      • Glossary or terms
      • Presentation Guidance
      • Equality, Diversity and Inclusion
      • Installation guide
      • Learning circles
      • Mentoring guidance
      • What to expect from your mentors
      • One-day projects
      • Pair programming
      • Portfolio
      • Questions for problem solving
      • Progress Logs
      • Final project report
      • Managing software projects
      • Project Presentations
      • Project roles
      • Projects
      • Retrospectives
      • Role Circles
      • Safeguarding policy
      • Technical Spikes
      • System requirements
      • Tech for Better
      • User Manuals
      • Wellbeing Support
      • project-docs
        • What makes a mentor?
        • Product Handover
        • Sprint Planning
        • Tech for Better Presentations
        • User Research & Usability Testing
    • foundation
      • full-stack
        • Learning Outcomes
        • project
      • testing
        • project
        • spikes
  • docs
    • Contributing to the curriculum
    • Curriculum intent
    • Curriculum process
  • src
    • About our curriculum
    • course
      • Code of Conduct
      • Docker
      • .NET and Umbraco
      • Getting started
      • Founders and Coders coursebook
      • KSB's
      • Mini projects
      • Revision checklist
      • Svelte
      • TypeScript
      • handbook
        • Software Developer Handbook
        • Software Foundation Handbook
      • precourse
        • Before you start the course
        • Installation List
      • syllabus
        • developer
          • app
            • learning-outcomes
            • project
            • schedule
            • spikes
          • introduction
            • learning-outcomes
            • project
            • resources
            • schedule
          • week00-pre-course
            • We'd like you to spend some time before starting the course working on useful fundamentals.
            • spikes
          • week01-project01-basics
            • Employability introduction
            • Homework
            • learning-outcomes
            • Week of September 9th
            • project
            • resources
            • schedule
            • spikes
          • week02-project02-chatbot
            • employability
            • Homework
            • learning-outcomes
            • Week of September 16th
            • project
            • resources
            • schedule
            • spikes
          • week03-project03-server
            • Learning Outcomes
            • Week of September 23th
            • The Amazin' Quizzer API Backend
            • resources
            • schedule
          • week04-project03-frontend
            • learning-outcomes
            • Week of September 30th
            • UI for Quizzer App
            • resources
            • schedule
          • week05-project03-test-deploy
            • Testing and deployment
            • Week of October 7th
            • project
            • resources
            • schedule
          • week06-project04-databases
            • learning-outcomes
            • Week of October 14th
            • project
            • Databases
            • schedule
          • week07-project04-authentication
            • Learning Outcomes
            • Week of October 21st
            • project
            • resources
            • schedule
          • week08-project04-test-deploy
            • Learning Outcomes
            • Week of October 28th
            • project
            • resources
            • schedule
          • week09-reading-week
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
          • week10-project05-DOTNET-intro
            • Learning Outcomes
            • overview
            • project
            • Resources
            • schedule
          • week11-project05-DOTNET-testing
            • Testing and deployment
            • Week of November 18th
            • project
            • Resources
            • schedule
          • week12-project05-DOTNET-deploy
            • Learning Outcomes
            • Week of November 25th
            • project
            • Resources
            • schedule
            • Spikes
          • week13-TFB-design
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Design Week Spikes
          • week14-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • DevOps Resources
            • schedule
            • Spikes
          • week15-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Spikes
          • projects
            • in-house-design
              • Learning Outcomes
              • Project
              • Resources
              • schedule
              • Design Week Spikes
        • foundation
          • Obsolete-full-stack
            • project
          • post-course
            • Homework
            • schedule
        • portfolio
          • fruit-shop
            • learning-outcomes
            • project
            • resources
          • game
            • learning-outcomes
            • project
            • resources
          • hobby-page
            • learning-outcomes
            • project
            • resources
          • movie-data
            • learning-outcomes
            • project
            • resources
          • project-gallery
            • learning-outcomes
            • project
            • resources
          • website
            • learning-outcomes
            • project
            • JavaScript
        • tfb
          • week 1
            • Introduction (45 minutes)
            • Further reading
          • week 10
            • content
            • resources
          • week 11
            • What will we be doing this week?
            • resources
          • week 12
            • What will we be doing this week?
            • Further reading
          • week 2
            • Discover (90 minutes)
            • resources
          • week 3
            • content
            • resources
          • week 4
            • Mapping the user journey (90 minutes)
            • resources
          • week 5
            • Figma Workshop 1 (90 minutes)
            • Further reading
          • week 6
            • Figma Workshop 2 (90 minutes)
            • resources
          • week 7
            • Product pitches & Selection (90 minutes)
            • resources
          • week 8
            • content
            • resources
          • week 9
            • content
            • resources
    • learn
      • DOTNET
        • Introduction to .NET
      • auth
        • Authenticating web apps
      • database
        • Persisting data with SQLite and Node
      • dotnet-two
        • Dependency injections and interfaces in .NET
      • form-validation
        • Form validation
      • react
        • Building client-side apps with React
      • server
        • HTTP servers with Node & Express
      • typescript
        • TypeScript
    • mentoring
      • design-week
        • Analysis Workshop
        • Code planning
        • Definition Workshop
        • Discovery Workshop
        • Figma introduction
        • Usability testing
        • User Research
    • resources
      • http
        • introduction
    • workshops
      • cookie-auth
        • index
      • creating-promises
        • index
      • css-layout
        • index
      • cypress-testing
        • index
      • database-testing
        • index
      • dev-tooling
        • Developer tooling
      • dom-challenge
        • index
      • dom-rendering
        • index
      • es-modules
        • index
      • express-middleware
        • Express middleware
      • first-class-functions
        • index
      • form-validation
        • index
      • functions-callbacks-async
        • Functions, callbacks, & async JavaScript
      • git-intro
        • Introduction to Git
      • git-terminal
        • Using Git in the terminal
      • git-workflow
        • Git workflow
      • github-projects
        • GitHub Projects Workflow Workshop
      • heroku-sql-challenge
        • index
      • html-forms
        • index
      • learn-a11y
        • index
        • starter-files
          • solution
            • Accessibility solution explanation
      • learn-fetch
        • index
      • learn-integration-testing
        • index
      • learn-testing
        • Learn testing in JavaScript
      • learn-unit-testing
        • index
      • node-error-handling
        • Node error-handling
      • node-express-server
        • Node and Express HTTP server
      • node-npm-intro
        • Node & npm introduction
      • node-postgres
        • Learn Postgres with Node
      • node-scripting-challenge
        • index
      • password-security
        • index
      • promise-practice
        • index
      • react-components
        • React components
      • react-fetch
        • index
      • react-forms
        • React forms
      • react-refactor-classes
        • index
      • react-state-effects
        • React state & effects
      • real-world-fetch
        • index
      • scope-challenge
        • Scope debugging challenge
      • semantic-html
        • index
      • server-side-forms
        • Server-side forms
      • session-auth
        • Session authentication
      • sql-intro
        • index
      • tdd-array-methods
        • index
Powered by GitBook
On this page
  • Functions are variables
  • Challenge
  • Functions are callable
  • Challenge
  • Inline functions
  • Challenge
  • Callbacks
  • Challenge
  • Async
  • Challenge
  • Workshop
  • Bonus (if you have time)
Export as PDF
  1. src
  2. workshops
  3. first-class-functions

index

In JavaScript functions are treated like any other variable. This is sometimes referred to as “first-class functions”. The concept can be confusing, so let's look at some examples.

Functions are variables

When you create a function in JS you are creating a normal variable:

function returnsOne() {
  return 1;
}
// we now have a variable named returnsOne

This is still true (and perhaps more obvious) for arrow functions:

const returnsOne = () => 1;

You can reference this variable the same way you would any other (using its name):

console.log(returnsOne);
// logs something like: `function returnsOne()`

Challenge

We can pass functions to other functions as arguments.

  1. Write a function named logger

  2. It should take one argument and log it to the console

  3. Call logger with the returnsOne function as an argument

Answer ```js function logger(thing) { console.log(thing); } logger(returnsOne); // function returnsOne() ```

Functions are callable

The main distinction between a function and other types of variable is that you can call a function. You call a function by putting parens (normal brackets) after it:

returnsOne();

Calling a function will run the lines of code inside of it. We can either reference the called function directly or assign it to a named variable.

console.log(returnsOne()); // 1

const myValue = returnsOne();
console.log(myValue); // 1

If the function returns nothing you'll get undefined:

function returnsNothing() {
  // doesn't have a return statement
}
const myValue = returnsNothing();
console.log(myValue); // undefined

Challenge

This is often a source of confusion when passing functions as arguments.

  1. Add another call to logger, but this time pass in returnsOne()

  2. Why do we see a different value logged?

    Answer ```js function logger(thing) { console.log(thing); } logger(returnsOne); // Logs the function itself: `function returnsOne()` logger(returnsOne()); // Logs the function's return value: `1` ```

  3. Edit logger to use typeof to log the type of the value

    Answer ```js function logger(thing) { console.log(typeof thing); } logger(returnsOne); // function logger(returnsOne()); // number ```

Inline functions

Another source of confusion is functions defined inline. This is a common pattern for passing functions as arguments to other functions (for example as event listeners):

window.addEventListener("click", (event) => {
  console.log(event.clientX, event.clientY);
});

Challenge

  1. Type the event listener code into your editor

  2. Extract the inline function and assign it to a variable

  3. Use the extracted function as your event listener

Answer ```js const handleClick = (event) => { console.log(event.clientX, event.clientY); }; window.addEventListener("click", (event) => handleClick(event)); // OR window.addEventListener("click", handleClick); // We don't need an extra arrow function if all it does is // forward arguments on to the function we actually care about ``` It's important to note that we don't want to _call_ our function when we pass it here. This won't work as we need to pass a function, not its return value: ```js const handleClick = (event) => { console.log(event.clientX, event.clientY); }; window.addEventListener("click", handleClick()); // this is equivalent to: // window.addEventListener("click", undefined); // since handleClick doesn't return anything ```

Callbacks

"Callback" is a scary word, but you've actually been using them the whole time. A callback is a function passed to another function as an argument. The name refers to what callbacks are usually used for: "calling you back" with a value when it's ready.

For example the addEventListener above takes a function that it will call when the "click" event happens. We're telling the browser "hey, call us back with the event info when that event happens".

Functions are effectively a way to delay execution of a block of code. Without them all our statements would run in order all in one go, and we'd never be able to wait for anything or react to user input.

Challenge

  1. Write a function one that takes a callback as an argument

  2. It should call the callback with 1

  3. Call your one function and pass in a callback that logs its argument

Answer ```js function one(callback) { callback(1); } one((x) => console.log(x)); // OR one(console.log); // the extra wrapper arrow fn isn't needed, since all it does // is forward its argument on to console.log (which is already a fn) ```

Async

The callback above might feel a bit pointless: why not just have the one function return 1? Callbacks make more sense when dealing with asynchronous code. Sometimes we don't have a value to return straight away.

For example network requests and timeouts can take multiple seconds to complete. JavaScript doesn't wait for these—it keeps on going and executes the next statements in the script.

console.log(1);
setTimeout(() => console.log(2), 1000);
console.log(3);
// 1, 3, then (after one second) 2

Our addEventListener from above can't return the click event, since it hasn't happened yet. So instead we pass a callback that it will run when it has the event.

Challenge

  1. Write a function asyncDouble that takes 2 arguments: a number and a callback

  2. It should use setTimeout to wait one second

  3. Then it should call the callback argument with the number argument multiplied by 2

  4. Call asyncDouble with 10 and a callback that logs whatever it is passed. You should see 20 logged after 1 second.

  5. Can you see why asyncDouble can't just return the doubled value?

Answer ```js function asyncDouble(num, callback) { setTimeout(() => callback(num * 2), 1000); } asyncDouble(10, (x) => console.log(x)); // OR asyncDouble(10, console.log); // (after one second) logs `20` ```

Workshop

Let's make some traffic lights.

  1. Write a function light that takes two arguments: a string and a callback

  2. It should wait 1 second, log the string and then call its callback argument

  3. Use light to log each colour of a traffic light sequence, in order, followed by "finished"

    • e.g. "green", "amber", "red", "amber", "green", "finished"

Bonus (if you have time)

Traffic light patterns are a bit more complex. The sequence should actually be "green", "amber", "red", "red" and "amber" (at the same time), "green". Without changing light, create the new sequence.

Previousfirst-class-functionsNextform-validation

Last updated 4 years ago