👨🏿‍💻
Learn
  • Learn And The Power Of Community
  • Intro
    • learn-co-curriculum/welcome-to-learn-verified
    • learn-co-curriculum/your-first-lab
    • learn-co-curriculum/environment-setup
  • Intro to tic tac toe
    • matz-readme
    • what-is-a-program?
    • hello world
    • Intro to irb
    • Reading-error-messages
    • Data-types
    • variable
    • Variable-assignment lab
    • String interpolation
    • Interpolation-super-power
    • Welcome to tic tac toe
    • Array
    • Tic tac toe board
    • Intro to methods
    • Puts print and return
    • Intro-to-tdd-rspec-and-learn
    • Methods and arguments
    • Say hello (lab)
    • Methods-default-arguments
    • ttt-3-display_board-example
    • ttt-4-display-board-rb
    • Intro-to-cli-applications
    • Greeting-cli
    • cli-applications in Ruby
    • Ruby-gets-input
    • Tic tac toe move
    • Truthiness-in-ruby-readme
    • booleans
    • conditional (if)
    • ttt-6-position-taken
    • ttt-7-valid-move
    • rspec-fizzbuzz
    • Looping-introduction
    • Loop
    • while-and-until-loop
    • Tic Tac Toe Turn lab
    • looping-while-until lab
    • Tic Tac Toe Play Loop (lab)
    • Tic Tac Toe Current Player (lab)
    • Intro to ruby iterators
    • Nested Arrays
    • Boolean Enumerators
    • Search Enumerators
    • Tic Tac Toe Game Status
    • tic-tac-toe
  • OOP tic tac toe
    • intro to oop
    • Intro-to-classes-and-instances
    • Classes-and-instances-lab
    • Instance-methods
    • Instance-methods-lab
    • Object Attributes
    • object-attributes-lab
    • Object Initialization
    • Object-initialize-lab
    • oop barking dog lab
    • Procedural-vs-oop
    • oop tic tac toe
  • Git and github
    • Intro to Version Control
    • Git Repository Basics
    • Git-basics-quiz
    • Forks-and-clones
    • Git Remotes and Github
    • Git Remotes and Github Codealong
    • Thinking Ahead: GitHub as Career Differentiator
    • Github Pull Requests
    • Git Collaboration
    • Git-collaboration-quiz
    • Git Basics Quiz
  • HTML
    • A-quick-tour-of-the-web
    • The-web-is-made-of-strings
    • What-makes-the-web-possible?
    • html-introduction
    • Your first-html-tag-lab
    • Nested-tags-and-attributes
    • Well-formed-html-document-lab
    • HTML elements types overview
    • Researching-HTML-elements
    • Separation-of-content-and-presentation
  • CSS
    • Introduction-to-css
    • introduction-to-css-code-along
  • Procedural Ruby
    • Regex-what-is-a-pattern
    • Regex-basics
    • Regex-lab
    • Regex-match-scan-grep-methods
    • learn-co-curriculum/method-arguments-lab
    • Method-scope
    • Return Values Lab
    • Debugging-with-pry
    • Method-scope-lab
    • Truthiness-code-challenge
    • If Statements Lab
    • Case-statements
    • Case-statements-quiz
    • Logic and Conditionals Quiz
    • Ternary Operators and Statement Modifiers lab
    • Looping Lab
    • looping-quiz
    • learn-co-curriculum/looping-times
    • countdown-to-midnight lab
    • Array introduction
    • Using Arrays
    • Array-CRUD-lab
    • Array-methods
    • Array-methods-lab
    • Square array lab
    • Collect and Return Values
    • Collect Lab
    • Badges and Schedules Lab
    • Oxford comma lab
    • Deli counter lab
    • Reverse Each Word Lab
    • Yield-and-blocks
    • Each Lab
    • Return from Yield Statements
    • My All? Lab
    • My Find Lab
    • Cartoon Collections Lab
    • Enumerators Code Challenge
    • Prime? Lab
    • Sorting
    • Sorting Lab
    • Introduction to Hashes
    • Using Hashes lab
    • Ruby-symbols
    • Hash iteration
    • Hash Iteration Lab
    • Hash Iteration with Collect
    • Intro to Nested Hashes
    • Building Nested Hashes
    • Building Nested Hashes Lab
    • Nested Hash Iteration
    • Nested Hashes Lab
    • Multitype Collections Lab
    • Iterating over Nested Hashes Codealong
    • Other Hashes Codealong
    • Hashes Manipulation Lab
  • OOP Ruby
    • OO Ruby Video: Object Orientation Overview
    • Object Accessors
    • Instance Variables lab
    • Video Review: Object Properties
    • Meowing Cat
    • Intro to Object Orientation - Ruby
    • oo basics lab
    • OO Basics with Class Constants
    • Self
    • OO School Domain lab
    • OO Counting Sentences lab
    • Class Variables and Methods
    • Class Variables and Methods Lab
    • Remembering Objects
    • Puppy Lab
    • Advanced Class Methods
    • Advanced Class Methods Lab
    • Video Review: Object Models
    • OO Email Parser lab
    • OO Anagram Detector lab
    • OO Cash Register lab
    • Intro to Object Relationships
    • Belongs to Object Lab
    • Has Many Object
    • Has Many Object Lab
    • Collaborating Objects Review
    • Collaborating Objects Lab
    • OO My Pets
    • oo kickstarter lab
    • OO Banking lab
    • Has Many Objects Through
    • Has Many Objects Through Lab
    • Intro to Inheritance
    • Intro to Inheritance Lab
    • Super
    • Super Lab
    • Intro to Modules
    • Intro to Modules Lab
    • Mass Assignment
    • Mass Assignment and Metaprogramming
    • Mass Assignment Lab
    • Custom Errors lab
    • OO Triangle lab
  • Scraping and project
    • Gems and Bundler
    • Scraping
    • Scraping Lab
    • Kickstarter Scraping Lab
    • Video Review: Object Orientation and Scraping
    • OO Ruby Object Orientation Video Review
    • Music Library CLI
    • Video Review: Music Library CLI
    • Tic-tac-toe with AI project
    • Student Scraper
    • CLI Data Gem Portfolio Project
    • CLI Data Gem Walkthrough
    • CLI Data Gem Walkthrough: Creating a CLI Scraper Gem
    • Common Anti-Patterns in CLI Data Gem
    • Student Example 1: Refactoring CLI Gem
    • Student Example 2: Refactoring CLI Gem
  • SQL
    • What is SQL
    • SQL Intro and Installation
    • SQL Database Basics
    • SQL Databases and Text Editors
    • SQL Data Types
    • SQL Inserting, Updating, and Selecting
    • Basic SQL Queries
    • SQL Aggregate Functions
    • SQL Aggregate Functions Lab
    • SQL Bear Organizer Lab
    • Edgar Codd and Table Relations
    • Table Relations
    • SQL JOINS
    • SQL Complex Joins
    • SQL Join Tables
    • Grouping and Sorting Data
    • SQL Joins Review Lectures
    • SQL Crowdfunding Lab
    • SQL Library Lab
    • Pokemon Scraper Lab
  • ORM And Active record
    • Why an ORM is Useful
    • Mapping Ruby Classes to Database Tables
    • Mapping Classes to Tables Lab
    • Mapping Database Tables to Ruby Objects
    • Mapping Database Rows to Objects Lab
    • Updating Records in an ORM
    • Updating Records in an ORM Lab
    • Preventing Record Duplication
    • ORMs Lab: Bringing It All Together lab
    • Dynamic ORMs
    • Dynamic ORMs with Inheritance
    • ActiveRecord Mechanics
    • Translating from ORM to ActiveRecord
    • Intro to Rake
    • Mechanics of Migrations
    • Writing Our Own Migrations
    • Migrations and Active Record Lab
    • ActiveRecord CRUD Lab
    • Advanced Finding Lab
    • ActiveRecord Associations
    • ActiveRecord Associations Lab
    • ActiveRecord Associations Lab II
    • ActiveRecord Associations Video Review
    • ActiveRecord Associations Video Review II
    • Video Review: Aliasing ActiveRecord Associations
    • Video Review: Blog CLI with ActiveRecord and Associations
  • Rack
    • How the Internet Works
    • Increasing Layers of Abstraction
    • Inspecting the Web with Rack (lab)
    • The HTTP Request
    • Dynamic URL Routes
    • Dynamic Web Apps with Rack (lab)
    • Rack Responses Lab
    • Rack Routes and GET Params Lab
    • HTTP Status Codes
    • Dynamic URLs and Status Codes Lab
    • Video Review: How The Web Works, Pt 1
    • Video Review: How the Web Works, Pt 2
  • Html
    • How the Web Works
    • Site Planning
    • HTML Fundamentals
    • HTTP Status Codes
    • video review how the web works pt 1
    • How the Web Works, Part 2: Overview
    • Setting Up a New Site
    • Document Structure
    • Text Formatting
    • HTML Tables
    • Html-images
    • HTML Links
    • Html backing-up changes
    • HTML Validation
    • Quiz - HTML Fundamentals
    • Dev Tools Super Power
    • HTML Lists
    • Html issue bot 9000 (lab)
    • HTML Forms and Iframes
    • HTML Map and Contact Form Code-along
    • HTML5 Media
    • HTML5 Video Embed Code-Along
    • HTML5 Semantic Elements
    • HTML5 Semantic Containers Code-along
    • HTML5 Quiz
  • CSS
    • CSS Fundamentals
    • CSS Styling Code Along
    • My Little Rainbow
    • CSS Kitten Wheelbarrow
    • CSS Graffiti Override Lab
    • CSS Issue Bot 9000
    • Your first deployment
    • The Box Model
    • Layout Types
    • Float
    • Clearfix
    • Centering
    • Column Structure
    • CSS Columns Code Along Exercise (lab)
    • Box Model & Page Layout
    • Using Z Index
    • Positioning
    • ZHW Shoes Layout (lab)
    • Zetsy (lab)
    • CSS Box Style Code Along
    • Animal Save (lab)
    • Building Responsive Sites
    • Intro to Responsive Media
    • CSS Media Queries
    • Working with Responsive Type
    • Responsive layout
    • The Viewport Property
    • Responsive Features Code-Along (lab)
    • Bootstrap Introduction
    • Bootstrap Code-Along
    • Bootstrap Grid System
    • Grid Layout Code-Along
    • Bootstrap Navbar Code-Along
  • Sinatra
    • What is Sinatra?
    • Sinatra From Scratch
    • Using the Shotgun Development Server (lab)
    • Sinatra Basics
    • Sinatra Hello World Basics (lab)
    • Routes in Sinatra
    • Sinatra Routes Lab
    • Intro To MVC
    • Sinatra MVC File Structure (lab)
    • Sinatra Views: Using ERB
    • Sinatra Views (lab)
    • Sinatra Basic Views Lab
    • Sinatra Views Lab II
    • Intro To Capybara
    • Dynamic Routes in Sinatra
    • HTML Forms and Params
    • Passing Data Between Views and Controllers in Sinatra
    • Sinatra Forms Lab
    • Sinatra Yield Readme
    • Integrating Models Sinatra Code-along
    • Sinatra MVC Lab - Pig Latinizer
    • Sinatra Basic Forms Lab
    • Sinatra Forms
    • Nested Forms Readme
    • Sinatra Nested Forms Lab: Pirates!
    • Lab Review-- Sinatra Nested Forms Lab: Pirates
    • Sinatra Nested Forms Lab: Superheroes!
    • Sessions and Cookies
    • Mechanics of Sessions
    • Sinatra Basic Sessions Lab
    • Using Sessions
    • Sinatra and Active Record CRUD
    • Sinatra Activerecord Setup
    • Sinatra ActiveRecord CRUD
    • User Authentication in Sinatra
    • Sinatra Sessions Lab - User Logins
    • Securing Passwords
    • Secure Password Lab
    • Sinatra Authentication- Overview
    • RESTful Routes
    • Restful Routes Basic Lab
    • Sinatra ActiveRecord Associations: Join Tables
    • Using Tux in Sinatra with ActiveRecord
    • ActiveRecord Associations in Sinatra
    • Sinatra Multiple Controllers
    • Sinatra and Active Record: Associations and Complex Forms
    • Sinatra Playlister (lab)
    • Welcome to NYC Sinatra! (lab)
    • Building a Site Generator, Part 1- Overview
    • Building a Site Generator, Part 2- Overview
    • Fwitter Group Project
  • Rails
    • Welcome To Rails
      • Rails Application Basics
      • Rails Static Request
      • Rails Hello World Lab
      • Rails Model View Controller
      • Intro to Rails- Overview
    • Intro to REST
    • Active Record Models and Rails
    • ActiveRecord Model Rails Lab
    • RESTful Index Action Lab
    • Rails Dynamic Request
    • Rails Dynamic Request Lab
    • Rails URL Helpers
    • Rails URL Helpers Lab
    • Rails form_tag
    • Rails form_tag Lab
    • Create Action
    • Create Action Lab
    • Index, Show, New, Create Lab
    • Edit/Update Action
    • form_for on Edit
    • Strong Params Basics
    • form_for Lab
    • Rails Generators
    • CRU with form_for Lab
    • Resource and Scaffold Generator
    • Rails Blog scaffold
    • Todo mvc assets and managing lists
    • Rails Forms Overview
    • ActiveRecord Validations
    • ActiveRecord Validations Lab
    • Validations in Controller Actions
    • Validations In Controller Actions Lab
    • Validations with form_tag
    • Validations with form_for
    • DELETE Forms and Requests
    • Testing in Rails
    • Validations with form_tag
    • CRUD With Validations Lab
    • Join the Fun rails
    • Activerecord lifecycle reading
    • Displaying Associations Rails
    • Active Record Associations Review
    • Forms And Basic Associations Rails
    • Forms And Basic Associations Rails Lab
    • Basic Nested Forms
    • Displaying Has Many Through Rails
    • Displaying Has Many Through Rails Lab
    • Has Many Through Forms Rails
    • Has Many Through Forms Rails Labs
    • Has Many Through in Forms Lab Review- Overview
    • Deep Dive into Nested Forms- Overview
    • Layouts And Templates in Rails
    • Rails Layouts And Templates Lab
    • Simple Partials
    • Simple Partials Lab
    • Partials with Locals
    • Partials with Locals
    • Refresher on MVC
    • Refactoring Views With Helpers
    • Refactoring Views With Helpers Lab
    • Model Class Methods
    • Optimal Queries using Active Record (lab)
    • Routing And Nested Resources
    • Nested Resource Routing Lab
    • Modifying Nested Resources
    • Modifying Nested Resources Lab
    • Namespaced Routes
    • Namespaced Routes Lab
    • Todomvc 2 lists have items
    • TodoMVC 3: Mark Items Complete
    • Todomvc 4 refactoring with partials and helpers
    • Todomvc 5 deleting items
    • Introduction to Authentication and Authorization
      • Cookies and sessions
      • Cookies and Sessions Lab
      • Sessions Controller
      • Sessions Controller Lab
      • Login Required Readme
      • Login Required Lab
      • Using has_secure_password
      • Has_secure_password lab
      • Authentication- Overviewn
      • OmniAuth
      • Omniauth Lab
      • Omniauth review lecture in todomvc
      • Authentication and authorization recap and gems
    • Rails Amusement Park lab
    • How to Find Gems
  • JavaScript
    • Intro to JavaScript
      • JavaScript Data Types
      • JavaScript Data Types Quiz
      • JavaScript Variables
      • JavaScript Comparisons
      • Conditionals
      • Logical Operators
      • Functions
      • Intro to Debugging
      • Intro to Testing
      • JavaScript Basics Quiz
    • Scope
      • Scope chain
      • JavaScript Practice Scope Lab
      • Lexical scoping
      • Errors and Stack Traces
      • Hoisting
    • Arrays And Objects
      • Objects
      • JavaScript: Objects and Arrays Quiz
      • Object Iteration
      • JavaScript Logging
      • Traversing Nested Objects
      • Filter
      • Map
    • Functions Revised
      • First-Class Functions Lab
      • First-Class Functions
      • First-Class Functions Practice
      • First-Class Functions Practice Lab
    • OOP
      • Creating Objects
      • Object Methods and Classes
      • Using Prototypes
      • Using Classes in Javascript
      • JavaScript This Walkthrough
      • This Code-along
      • Bind, Call, and Apply Readme
      • Bind, Call, Apply Lab
      • Object Relations
      • Association Methods in Javascript
      • Class Relations Lab
      • JavaScript Closures and Higher Order Functions
      • Closures Lab
      • JavaScript Arrow Functions
      • Daily Lunch Lab
    • DOM
      • Introduction to the DOM
      • Introduction to the DOM Lab
      • More on the DOM
      • Creating and Inserting DOM Nodes
      • The DOM Is a Tree
      • Listening to Nodes
      • Modify HTML With jQuery
      • Modifying HTML Lab
      • jQuery Selectors
      • Document.ready
      • Acting On Events Lab
      • DOM Quiz
    • Templates
      • Introduction to CSS
      • CSS Quiz
      • CSS Libraries
      • CSS Libraries Lab
      • Intro to Templates
      • Template Engines
      • Template Engines Lab
      • Advanced Templating
      • Advanced Templating Lab
    • Asynchronous JavaScript
      • Intro to XHR Code Along
      • Hitting APIs Lab
      • Advanced AJAX Lab
      • AJAX and Callbacks
      • AJAX and Callbacks Lab
      • REST Refresher
      • REST Quiz
      • Fetch
      • JavaScript fetch() Lab
      • Intro to Mocha
      • Testing with Spies
      • Testing with Mocks and Stubs
  • Rails and JavaScript
Powered by GitBook
On this page
  • Objectives
  • Introduction
  • Statements vs. expressions
  • Function expressions
  • Functions are objects
  • Assigning functions to variables
  • Adding properties to a function
  • Storing functions in an array
  • Storing functions in objects
  • Returning functions from functions
  • Functions passed as arguments
  • Immediately-invoked function expressions
  • Anonymous function expressions
  • Conclusion
  • Resources
  1. JavaScript
  2. Functions Revised

First-Class Functions

Objectives

  • Explain the difference between a statement and an expression.

  • Use function expressions instead of function declarations and understand the differences.

  • Understand that functions are special objects that — among many other things — can be stored in variables and other data structures, can contain key-value pairs (properties), and can be passed to and returned from other functions.

  • Recognize an IIFE and break down what's going on with its unusual syntax: (function () {})()

Introduction

Let's talk about functions. "Ugh, again?! We've already covered functions," you complain. Well, we've talked about functions before, but now it's time to really talk about functions. Bear with us, and prepare to have your mind blown.

Statements vs. expressions

Before we dive headlong into functions, let's take a minute to talk about the fundamental building blocks of JavaScript code: expressions and statements. A statement is a unit of code that accomplishes something but does not produce a value. An expression is a unit of code that produces a value.

Many of the common keywords we've encountered form statements:

  • Variable declarations: const, let, var

  • Iteration: for, for...in, for...of, while

  • Control flow: if...else, switch, break

  • Debugging: debugger

All of those keywords are extremely useful, but none of them generate a value on their own. Take this if statement:

The expression inside of the if statement, 6 + 9, produces a value: the number 15. The if statement itself, however, produces no value. We can assign the expression 6 + 9 to a variable, but we can't assign that if statement to one:

const myVar = 6 + 9;

myVar;
// => 15

const myOtherVar = if (true) { 6 + 9; };
// ERROR: Uncaught SyntaxError: Unexpected token if

That Unexpected token error message is JavaScript telling us, "Hey, that keyword is for creating statements — stop trying to use it as though it's an expression!" A few more examples:

const myVar = debugger;
// ERROR: Uncaught SyntaxError: Unexpected token debugger

const myVar = const myOtherVar = 6 + 9;
// ERROR: Uncaught SyntaxError: Unexpected token const

const myVar = while (true) { 6 + 9; };
// ERROR: Uncaught SyntaxError: Unexpected token while

Top Tip: If you're struggling a bit with the difference between a statement and an expression, let's try thinking about it in a slightly different way. Statements can be used to hold data (const, let, var), iterate over data (for, for...in, for...of, while), control the flow of data (if...else, switch, break), and debug data (debugger). Contrast that with expressions, which produce data. A JavaScript program is effectively a series of statements that control, organize, and structure a series of expressions.

If you're still having some trouble with the distinction, there's an excellent blog post by Dr. Axel Rauschmayer linked at the bottom of this lesson. But what does all of this stuff about expressions and statements have to do with functions?

Function expressions

When we first learned about functions, we learned about function declarations, which are a type of statement. That is, when we declare a function in the standard way, it does not produce a value:

However, the function keyword is adaptable. When it's the first thing in a line of code, it forms a function declaration that creates a new function in memory but does not immediately produce a value. When it's placed anywhere except at the start of a line, it forms a function expression that creates a new function and immediately returns that function as a value:

(function() {});
// => ƒ () {}

String literals result in new strings, array literals result in new arrays, object literals result in new objects, and function expressions result in new functions:

'Hello, world!'
// => "Hello, world!"

[]
// => []

{}
// => {}

(function () {})
// => ƒ () {}

NOTE: The parentheses surrounding the above anonymous function are so that the function keyword isn't the first thing in the line of code. Parentheses used in this way are the grouping operator (as in 2 * (3 + 4)), and they don't affect the value produced by the expression:

'Hello, ' + 'world!';
// => "Hello, world!"

Parentheses around a function expression are only required if the function keyword would otherwise be the first thing in a line of code.

Okay, great, so we can create functions with function expressions. So what?

Functions are objects

  • A function can be assigned to a variable.

  • A function can be stored in a data structure.

  • A function can be the return value of another function.

  • A function can be passed as an argument to another function.

In a previous lesson, we told you to start thinking about functions as objects because, well, they are. A JavaScript function is simply a JavaScript object with a few added goodies. That means that everything we can do to an object can also be done to a function.

Assigning functions to variables

A function expression results in a function. Just like we can store an object in a variable, we can also store a function in a variable:

const myObj = {};

const myFunc = function() {
	return 6 + 9;
};

Since the result of the function expression is a function object, that variable now contains a function. What can we do to functions? We can invoke them!

Now if we wrote:

Should we expect to see 15 ?? No, we'll see the definiton of the function itself. Our variables stores a reference to the function itself. We can call it whenever we want to.

Since typing myFunc returns a function, we can invoke that function like we invoke any other function with ()

We can see 15 by typing:

myFunc();
// => 15

myFunc() + 1;
// => 16

myFunc + 1;
// => "function (){...}1"

Function expressions and hoisting

One thing to note when you're debating whether to use a function declaration or a function expression stored in a variable: function expressions are not hoisted. Remember, hoisting is the somewhat ill-fitting name for the process whereby the JavaScript engine stores function (and variable) declarations in memory during the compilation phase. Since they're already stored in memory by the time the execution phase starts, we can refer those 'hoisted' functions before their lexical declaration — that is, above where they're written in the code:

sayHi();

function sayHi() {
	console.log('Hi');
}

The above code works perfectly fine. Try it out in your browser's console. Contrastingly, function expressions are not hoisted. The JavaScript engine ignores them during the compilation phase, instead evaluating them during the execution phase. The following code will result in an error because variables declared with const aren't hoisted:

sayHello();

const sayHello = function() {
	console.log('Hello');
};
// ERROR: Uncaught ReferenceError: sayHello is not defined

Even if we use the dreaded var, the variable declaration will be hoisted but the assignment — where the function is instantiated and assigned to the variable — doesn't happen until the execution phase. Therefore we see a different error, this one telling us that sayHello is not a function:

sayHello();

var sayHello = function() {
	console.log('Hello');
};
// ERROR: Uncaught TypeError: sayHello is not a function

The sayHello variable is hoisted this time, but it contains undefined until the assignment line is reached. We can't invoke undefined, so sayHello() throws an error.

Top Tip: Storing a function expression in a const-declared variable is a good default strategy. We get all of the intelligent scoping behavior provided by const, allowing us much more intuitive control over when and where the function is available for use.

Passing by reference

Like all JavaScript objects, functions are passed by reference. When a new function is created, it's stored at a specific location in memory. When we assign a function expression to a variable, we're not actually storing the entire function in that variable — we're simply storing a reference to the location in memory where the function lives. If we assign the value of that first variable to a new variable, the new variable also points at the same location in memory:

const original = function() {
	console.log("I'm the original!");
};

const copy = original;

copy();
// LOG: I'm the original!

If we modify the function, we're changing the object in memory, so every reference to the function will see the modifications:

copy.newProperty = "I'm a new property!";

original.newProperty;
// => "I'm a new property!"

However, if we simply reassign the variable to a new function, it no longer points at the same location in memory:

let original = function() {
	console.log("I'm the original!");
};

const copy = original;

original = function() {
	console.log("I'm a new function!");
};

copy();
// LOG: I'm the original!

original();
// LOG: I'm a new function!

Adding properties to a function

Since a function is just a special object, we can add properties to functions and then access them:

const myFunc = function() {
	return 6 + 9;
};

myFunc.favoriteNumber = 42;
// => 42

console.log("myFunc()'s favorite number is", myFunc.favoriteNumber);
// LOG: myFunc()'s favorite number is 42

Storing functions in an array

We can store functions as elements in an array:

const arrayOfObjects = [
	{ name: 'Sandi Metz' },
	{ name: 'Anita Borg' },
	{ name: 'Ada Lovelace' }
];

const arrayOfFunctions = [
	function() {
		console.log('Functions');
	},
	function() {
		console.log('are');
	},
	function() {
		console.log('so');
	},
	function() {
		console.log('cool!');
	}
];

When we access the various indexes in our array, we're retrieving those stored functions:

arrayOfFunctions[0];
// => ƒ () { console.log('Functions'); }

arrayOfFunctions[3];
// => ƒ () { console.log('cool!'); }

And, one more time, what's that fun thing we can do to any function? We can invoke it! How do we invoke it? With the invocation operator:

arrayOfFunctions[0]();
// LOG: Functions
arrayOfFunctions[1]();
// LOG: are
arrayOfFunctions[2]();
// LOG: so
arrayOfFunctions[3]();
// LOG: cool!

for (const fn of arrayOfFunctions) {
	fn();
}
// LOG: Functions
// LOG: are
// LOG: so
// LOG: cool!

Storing functions in objects

We can also store functions as properties of an object:

const ada = {
	fullName: 'Ada Lovelace',
	greet: function(name) {
		console.log(`Hi there ${name}, I'm Ada Lovelace.`);
	},
	claimToFame: function() {
		console.log('I was the first computer programmer.');
	}
};

ada.fullName;
// => "Ada Lovelace"

ada.greet;
// => ƒ (name) { console.log(`Hi there ${name}, I'm Ada Lovelace.`); }

ada.greet();
// LOG: Hi there undefined, I'm Ada Lovelace.

ada.greet('Vince');
// LOG: Hi there Vince, I'm Ada Lovelace.

ada.claimToFame();
// LOG: I was the first computer programmer.

NOTE: When a function is stored in an object, we call it a method. It's also still a function, of course — methods are a subset of functions. We'll go much deeper into this in the lessons on object-oriented JavaScript, but keep the terminology in mind. A good rule of thumb: if you need to use the dot operator to invoke the function (as in ada.greet() instead of simply greet()), it's a method. For a common example, think of console.log(). We're invoking the log() method on the console object.

Returning functions from functions

Functions can return any kind of data: strings, numbers, objects... you name it. Well, since functions are themselves merely objects, what's stopping us from returning a function from a function? Nothing! Here we create a function that assembles and returns other functions:

const createDivisibleFunction = function(divisor) {
	return function(num) {
		return num % divisor === 0;
	};
};

Then let's store the returned functions in variables so that we can reference and invoke them:

const divisibleBy3 = createDivisibleFunction(3);

const divisibleBy5 = createDivisibleFunction(5);

divisibleBy3;
// => ƒ (num) { return num % divisor === 0; }

divisibleBy5;
// => ƒ (num) { return num % divisor === 0; }

divisibleBy3(9);
// => true

divisibleBy3(10);
// => false

divisibleBy5(9);
// => false

divisibleBy5(10);
// => true

Top Tip: In a situation where we need a lot of similar but slightly different functions, this is a great pattern for cutting down on repetitive code. Instead of declaring 100 different functions, we can declare a single function and invoke it 100 times, passing in different arguments each time. We'll still end up with the same 100 functions, but we drastically reduced the amount of code we had to write.

It's turtles all the way down

There's nothing stopping us at a function that returns a function, though. How about a function that returns a function that returns a function that returns a... well, you get the idea:

const howManyLicks = function() {
	return function() {
		return function() {
			return function() {
				return function() {
					return function() {
						return function() {
							return function() {
								return function() {
									return function() {
										console.log(
											'does it take to get to the Tootsie Roll center of a Tootsie Pop?'
										);
									};
								};
							};
						};
					};
				};
			};
		};
	};
};

When we invoke the function stored inside the howManyLicks variable, it returns another function:

howManyLicks();
// => ƒ () { return function () { return function () { return function () { ...

One lick down, nine more to go. When we invoke the function returned by the invocation of the first function, we get another function:

howManyLicks()();
// => ƒ () { return function () { return function () { return function () { ...

We can continue in this manner all the way down the nested functions:

howManyLicks()()()()();
// => ƒ () { return function () { return function () { return function () { ...

howManyLicks()()()()()()();
// => ƒ () { return function () { return function () { console.log('does it ...

Until, finally, we reach the center:

howManyLicks()()()()()()()()();
// => ƒ () { console.log('does it take to get to the Tootsie Roll center of ...

howManyLicks()()()()()()()()()();
// LOG: does it take to get to the Tootsie Roll center of a Tootsie Pop?

Please don't ever do this in your actual code. The deeply nested example is simply meant to familiarize ourselves with the combination of these ideas:

  1. We can invoke functions.

  2. Functions can return other functions.

  3. When a function returns another function, we can invoke its return value because it's a function!

Functions passed as arguments

We already encountered this during the introduction to callback functions, but the concept is important enough to reiterate here: functions can be passed into other functions as arguments. Take a look at the following example:

function hid(fn) {
	console.log('Inside hid()');

	return fn;
}

const den = function(fn) {
	console.log('Inside den()');

	return fn;
};

function mess(cb) {
	console.log('Inside mess()');

	cb();
}

const age = function() {
	console.log('Inside age()');
};

hid(den)(mess)(age);
// LOG: Inside hid()
// LOG: Inside den()
// LOG: Inside mess()
// LOG: Inside age()

The final line, hid(den)(mess)(age), looks super weird, but let's break it down. First, we invoke the hid() function, and we pass the value stored in the den variable in as the lone argument: hid(den). An anonymous function is stored in den, and all hid() does is return the passed-in argument. If we stop there, the return value of hid(den) is the function stored in den:

hid(den);
// LOG: Inside hid()
// => ƒ (fn) { console.log('Inside den()'); return fn; }

So invoking hid(den) logs out the first message and then returns a function. The returned function accepts one argument, logs out a second message, and then returns the passed-in argument. What do we like to do with functions? Invoke 'em! Invoking hid(den)() would do the trick, but let's also pass in another function as the fn parameter:

hid(den)(mess);
// LOG: Inside hid()
// LOG: Inside den()
// => ƒ mess (cb) { console.log('Inside mess()'); cb(); }

And right on cue, it returns another function! This one also accepts a single argument, then logs out a message, and finally invokes the passed-in argument. If we invoke the returned function without passing an argument, we get a pretty descriptive error:

hid(den)(mess)();
// LOG: Inside hid()
// LOG: Inside den()
// LOG: Inside mess()
// ERROR: Uncaught TypeError: cb is not a function
//          at mess (:16:3)
//          at :1:15

Since we didn't pass any arguments, the cb parameter inside mess() contained undefined. And when the JavaScript engine hit the cb() line inside mess(), it yelled at us: "Hey, cb doesn't contain a function — it contains undefined. I can't invoke this!" When we pass in a function, such as age(), everything works swimmingly:

hid(den)(mess)(age);
// LOG: Inside hid()
// LOG: Inside den()
// LOG: Inside mess()
// LOG: Inside age()

Immediately-invoked function expressions

An immediately-invoked function expression (usually abbreviated to IIFE) is exactly what it says on the tin: it's a function expression that we invoke immediately. Here's a function expression that returns a function object:

(function() {
	console.log("Help, I've been invoked!");
});
// => ƒ () { console.log("Help, I've been invoked!") }

What can we do with that returned function object? We can invoke it... immediately:

(function() {
	console.log("Help, I've been invoked!");
})();
// LOG: Help, I've been invoked!

We can pass arguments into the invocation operator just like any old function:

(function(name, year, claimToFame) {
	console.log(`Hi, I'm ${name}, I was born in ${year}, and I ${claimToFame}!`);
})('Ada Lovelace', 1815, 'was the first computer programmer');
// LOG: Hi, I'm Ada Lovelace, I was born in 1815, and I was the first computer programmer!

(function(name, year, claimToFame) {
	console.log(`Hi, I'm ${name}, I was born in ${year}, and I ${claimToFame}!`);
})('Grace Hopper', 1906, 'invented one of the first compilers');
// LOG: Hi, I'm Grace Hopper, I was born in 1906, and I invented one of the first compilers!

We won't be using IIFEs much until we introduce closures, but it's an ubiquitous construct that you're sure to come across when searching StackOverflow and other resources.

Anonymous function expressions

We mentioned this in a previous lesson as well, but now we can put some more definite terms behind the concept. A function declaration must have a name; the JavaScript engine requires that we assign it an identifier that we can then use to refer to the function object in memory. Forgoing the name results in the following error message:

function () {}
// ERROR: Uncaught SyntaxError: Unexpected token (

The engine is saying, "Hey, I expected to see an identifier after the function keyword, but all I found was this silly parenthesis. That's not the start of a valid identifier!"

However, there's no such constraint on function expressions. You can add a name if you want:

(function namedFunctionExpression1() {});
// => ƒ namedFunctionExpression1() {}

const myFunc = function namedFunctionExpression2() {};

myFunc;
// => ƒ namedFunctionExpression2() {}

But it isn't necessary:

(function() {});
// => ƒ () {}

const myFunc = function() {};

myFunc;
// => ƒ () {}

Most of the time, an anonymous function expression will suffice. It's a bit easier to read and keeps our code less cluttered. That being said, there's one main benefit to naming your function expressions: better stack traces. This anonymous stack trace doesn't give us a lot to go on:

(function() {
	thisWillThrowAnError;
})();
// ERROR: Uncaught ReferenceError: thisWillThrowAnError is not defined
//          at :1:16
//          at :1:40

This one includes the function expression's name and is consequently a bit easier to locate and debug:

(function nowWithAName() {
	thisWillThrowAnError;
})();
// ERROR: Uncaught ReferenceError: thisWillThrowAnError is not defined
//          at nowWithAName (:1:29)
//          at :1:53

Conclusion

This lesson introduces a ton of new things to think about when dealing with functions in JavaScript, but you're hopefully starting to see just how powerful functions are. We'll be discussing many of these new concepts in greater depth as we continue to explore the JavaScript language. It's important that you practice and familiarize yourself with these fundamental ideas because they are the building blocks that we'll expand on and compose into increasingly complex and powerful patterns.

Resources

PreviousFirst-Class Functions LabNextFirst-Class Functions Practice

Last updated 5 years ago

In JavaScript, functions are what's known as of the language. That means functions have the following four abilities:

View on Learn.co and start learning to code for free.

first-class citizens
Wikipedia — First-class function
StackOverflow — What is meant by 'first class object'?
Helephant — Functions are first class objects in javascript (Wayback Machine)
2ality — Expressions versus statements in JavaScript
MDN — Statements and declarations
First-Class Functions
Vince McMahon is interested.
Vince McMahon is excited.
Vince McMahon is disinterested.
Vince McMahon is surprised.
Vince McMahon is intrigued.
Vince McMahon is startled.
Vince McMahon has lost it.