Side Effects & pure functions Flashcards
What actions qualify as a function side effect?
- It reassigns any non-local variable.
- It mutates the value of any object referenced by a non-local variable.
- It reads from or writes to any data entity (files, network connections, etc.) that is non-local to your program.
- It raises an exception.
- It calls another function that has any side effects that arenotconfined to the current function. For instance, if you call a function that mutates an argument, but that argument is local to the calling function, then it isn’t a side effect. (See the example with
sort
later in this assignment.)
What side effect does this have?
let number = 42;
function incrementNumber() {
number += 1;
}
side effect: reassigning ‘number’ defined in outer scope
What side effect does this have?
let letters = [‘a’, ‘b’, ‘c’];
function removeLast() {
letters.pop();
}
// side effect: alters the array referenced by letters
What IO actions count as side effects?
- Reading from a file on the system’s disk
- Writing to a file on the system’s disk
- Reading input from the keyboard
- Writing to the console
- Accessing a database
- Updating the display on a web page
- Reading data from a form on a web page
- Sending data to a remote web site
- Receiving data from a remote web site
- Generating random numbers with
Math.random()
- Interacting with devices that change the system state in such a way that is observable, such as:
- The mouse, trackpad, or other pointing devices
- The random number generator
- The audio speakers
- The camera
What side effect does this have?
function divideBy(numerator, denominator) {
if (denominator === 0) {
throw new Error(“Divide by zero!”);
}
return numerator / denominator;
}
// side effect: raises an exception
how does exception catching impact side effects?
function divideBy(numerator, denominator) {
try {
if (denominator === 0) {
throw new Error(“Divide by zero!”); // side effect: raises an exception
}
} catch (error) {
console.log(error.message);
return undefined;
}
return numerator / denominator;
}
What are pure functions?
Pure functionsare functions that:
- Have no side effects.
- Given the same set of arguments, the function always returns the same value during the function’s lifetime. This rule implies that the return value of a pure function depends solely on its arguments.