Side Effects & pure functions Flashcards

1
Q

What actions qualify as a function side effect?

A
  1. It reassigns any non-local variable.
  2. It mutates the value of any object referenced by a non-local variable.
  3. It reads from or writes to any data entity (files, network connections, etc.) that is non-local to your program.
  4. It raises an exception.
  5. 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 withsortlater in this assignment.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What side effect does this have?

let number = 42;
function incrementNumber() {
number += 1;
}

A

side effect: reassigning ‘number’ defined in outer scope

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What side effect does this have?

let letters = [‘a’, ‘b’, ‘c’];
function removeLast() {
letters.pop();
}

A

// side effect: alters the array referenced by letters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What IO actions count as side effects?

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What side effect does this have?

function divideBy(numerator, denominator) {
if (denominator === 0) {
throw new Error(“Divide by zero!”);
}

return numerator / denominator;
}

A

// side effect: raises an exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how does exception catching impact side effects?

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are pure functions?

A

Pure functionsare functions that:

  1. Have no side effects.
  2. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly