Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
Lesson 8, Topic 2
In Progress

JavaScript: Functions as Data

Yasin Cakal 25 Nov 2021
Lesson Progress
0% Complete

We can assign functions to variables and reassign them to new variables in JavaScript, just like any other data type.

Below is an excessively long function name that detracts from the readability of any code that uses it. Assume this function performs critical work and must be called repeatedly!

const highAlertMessageForDrivers = () => {
    console.log("Ambulance on road!");
};

What if we wanted to rename this function but didn’t want to throw away the source code? We can reassign the function to a variable with a short name like this:

const urgent = highAlertMessageForDrivers;
urgent();

Our original function is referenced by the variable urgent. If we looked up the addresses in memory for urgent and highAlertMessageForDrivers, they would both point to the same location. With parentheses, we can call our new urgent() function as if that was the name we originally gave it.

Notice how we set the value of the urgent variable to highAlertMessageForDrivers without using parentheses. We want to assign the function’s value, not the value it returns when it’s called.

Functions are first-class objects in JavaScript. JavaScript functions can have properties and methods. Because functions are objects, they have properties like .length and .name, as well as methods like .toString(). More information on function methods and properties can be found in the documentation.

Responses

Leave a Reply

%d bloggers like this: