ga-wdi-boston / js-functions-ins-and-outs

JavaScript Function Arguments and Return Values.
Other
2 stars 174 forks source link

The memo example is wrong, or I don't understand the intent. Help? #49

Open jrhorn424 opened 7 years ago

jrhorn424 commented 7 years ago

See annotations for questions

const memoFactory = function (memo) {
  let total = 0
  // notice the lack of a local variable here for closure, as well as the lack of a parameter in the
  // below, returned function
  return function () {
    total+= 1
    return total + ": " + memo // where should this be? Is it defined?
  }
}

const memo = memoFactory() // looks like memo isn't defined

 // looks like we're passing an argument to a generated function that names no parameters
const entryMonday = memo("Monday was fun")
const entryTuesday = memo("I liked Tuesday") // ditto
const entryWednesday = memo("Ugh Wednesday") // ditto

console.log(entryMonday) // "1: Monday was fun" // no, what is actually produced is "1: undefined"
console.log(entryTuesday) // "2: I liked Tuesday" // no, what is actually produced is "2: undefined"
console.log(entryWednesday) // "3: Ugh Wednesday" // and so on
jrhorn424 commented 7 years ago

Originally reported by @MicFin at my request over in #48:

This example may be incorrect to show error and then fix but it is not clear. https://github.com/ga-wdi-boston/js-functions-ins-and-outs#code-along---return-new-functions

- const memoFactory = function (memo) {
+ const memoFactory = function () {
 let total = 0

-  return function () {
+  return function (memo) {
   total+= 1
   return total + ": " + memo
 }
}
gaand commented 7 years ago

I don't know where you example came from, it's too complicated to start with and I don't know who wrote the code, but this simple closure is the point, and is the code I wrote back whenever:

const memoFactory = function (memo) {
  return function () {
    return memo
  }
} 
gaand commented 7 years ago
const bob = memoFactory('bob')
bob()
// => 'bob'
const dave = memoFactory('dave')
dave()
// => 'dave'
bob === dave
// => false
bob()
// => 'bob'
dave()
// => 'dave'
MicFin commented 7 years ago

I believe a counter was added because developers were struggling with why something like this would be used when you could just do...

const bob = 'bob'
const dave = 'dave'
bob
// => 'bob'
dave
// => 'dave'

Silly, but it is something new developers think of.

gaand commented 7 years ago

The point is to show that the name memo in the returned functions point to different objects. You wouldn't do exactly this in the real world, but showing a different way to accomplish the same thing is often valuable. two parameters, This is the intro to closure. The counter example is where you're supposed to end.