[Arguments Optional] Looking for a good explanation of closures. What did I do here and how the heck does this work[Spoiler alert!]

Hey,
Link to the algorithm challenge : https://www.freecodecamp.com/challenges/arguments-optional#

I read the MDN article on this topic and a video on youtube. Then I wrote something blindly and after couple of trials it got a pass.

But as I think it’s duct tape code which I don’t know how it worked actually, I thought I’ll post it here:

function addTogether(x) {
 if (arguments.length === 1 && typeof arguments[0] === "number") {
   return function (y) { 
 if (typeof arguments[0] === "number")  return x + y;
  }; // end inner if
 } // end outer if
  else {
    if (typeof arguments[0] !== "number"|| typeof arguments[1] !== "number") {
      return undefined;
    } // end if
    return arguments[0] + arguments[1];
  } // end else
} // end addTogether(x)

addTogether(2)([3]);
  1. Could someone explain to me, how did it work and why?
  2. How did this know that y argument refers to the[3] in addTogether(2)([3]); . I mean - what happens here underneath?

I know these are quite absurd questions to my own code, but help appreciated :smiley:

1 Like

Wow, the fact that i made it right, overwhelms me :smiley: Thanks for so much work put here, P1xt :slight_smile:

Anyway, i’ve got to replay some videos about closures to finally know what i’m doing :joy:

i heard of this series, will take a look :slight_smile: thnx

Here’s my code, which surely could be refactored, but I was amazed that I got it done within a day :slight_smile:
I still don’t understand closures totally, but I’m stoked to have finished all the required Algorithm Challenges for the course :slight_smile:

function addTogether(a) {
  // set up variables to make code cleaner
  const    argLen1   = arguments.length === 1,
           argLen2   = arguments.length === 2,
           arg0Type  = typeof arguments[0] === "number",
           arg1Type  = typeof arguments[1] === "number";
  
  // if argument is a number return a + b
  if ( argLen1 && arg0Type ) {
    let sumTwoAnd = function arg2 (b) {
      if ( typeof b === "number" ) {
        return a + b;
      }  
    };
    
    return sumTwoAnd;
    
    // if more than 2 arguments, simply add them together  
  } else if ( argLen2 && arg0Type && arg1Type ) {
    
    return arguments[0] + arguments[1];
    
  }
}
// win at life (and Free Code Camp!) 
addTogether(2)(3);
1 Like

I dont understand the task. Cant comprehend it.

1. Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

Okay, what the heck is ‘expects one argument and returns the sum’?
Say, user have comitted input:’ addTogether(2).’ Okay, done. We have single argument and this argument is 2. My code registers this input and ‘returns a function’ - summons some special functionSpecificallyDesignedForThisCase(). How this new function ‘expects’ things? Does it ask for user input again? 'Hi, this is another function which was returned because your previous input was with single argument. Now I expect a new input from you and it should be single argument which im gonna sum!'
Or it is being feeded its argument from somewhere before? ‘returns the sum’ - sum of WHAT? We have 1 argument at this point how can you sum 1 argument?

Ive done 287 challenges to this point and never had a single reading comprehension problem but this explanation leaves me absolutely confused!

1 Like

Any tips? Sorry, but i really am frustrated with this challenge, cant even start doing it without understanding of task.

First of all I must apologize for not answering earlier despite all my crying for attention. I just went to bed and didnt notice your answer.

Yesterday when i was wrecking myself around this problem I also asked some folks in chat. Some of them (@codezmy ? @nasperth ? I dont quite remember) offered pretty elaborate explanations. However this was wasted on me and I still didnt get the concept. So when i came home at the evening all that was left in my completely blank mind was that they used ‘f’ letter to name inner function.

So i read again Closure article and fiddled with different code variations for like an hour and then it settled itself down into code that somehow passes challenge:

> function addTogether(x){
>   function f(y){
>     if (!Array.isArray(y)){return x+y;}}
>   if(arguments.length===2&&arguments[1]&&arguments[0]&&typeof arguments[0]=='number'&&typeof arguments[1]=='number'){return arguments[0]+arguments[1];}
>  else if (arguments.length===1&&typeof arguments[0]==='number'){
>    return f;
>  }
> }

> var f = addTogether();

> addTogether(2);

Still, i dont understand this code fully - i arrived into it from sheer tenacious trial and error, not following some mindful approach.

I do grasp the very ‘basic outline’ of whats happening in your example. Like, first value (assigned to var cat) is passed to outer function and second value (inside calling statement with console.log) is passed to inner function. But everything beyond that is a mystery. Hell, i dont even understand why my code passes challenge in the first place…

1 Like

Hi man,

I could not agree more. I got really angry when I read that challenge. I had exactly the same questions than you do (or did). Nothing makes sense and you don’t even see the purpose of it. They throw at you a challenge that needs closures to be solved without the smallest hint that you will need such a thing. It is quite unfortunate, specially taking into account that closures are not the most intuitive concept. In fact, if a challenge does need some extra explanation this is the one.

I am not going to help you with closures because I cant! :grinning: I just wanted to tell you that lately I am doing great progress at controlling my frustration when this kind of thing happens, which is a good thing because anger and frustration blind my understanding. For me it has been of great help to read and listen other coders reflect upon the fact that as far as it is free we should never get angry with the tools and resources that other people let us use… no matter what bugs they may have. The code universe does not owe us anything. The second advice that helps me a lot is to take these mistakes as a taste of what real coders everyday reality is… because most of the time they have to fix crappy code wrote by someone else (who was getting paid).

I admit that I have written this more for myself than for you, but maybe it may feel some other frustrated freecodeCamper that he/she is not alone.

Cheers

4 Likes

Hi Jack,

I have just finished this challenge with much struggle and some frustration (closures have made me their bitch :grin:, English is not my first language so I hope I am not breaking any rules by saying this).

I have seen how you have declared your variables, as constants and also that double assignment / compare (= xxx===yy) thing. I also see people using the fat arrows (like P1xt does above)… so my question is… where have you picked up those techniques? are they all part of the ECMA6 new features?

I do like the idea of clean code, not only because it is more readable, but also because it helps me to understand the concepts better as I try to order and clean things.

Hi there,

Your English is awesome! Well done.

While FCC is amazing, I have been using a TON of other resources to learn programming.
I’m a bit exhausted to be honest, because I feel like my education is just pieced toegther with bits from everywhere.
I read blogs, watch videos, read eBooks, I talk on forums, I ask so many stupid questions, and recently I have just started getting lessons from a tutor!

I want to learn faster, and I want to learn how to be more strategic when coding.
Although the best resources for me to date have been the video courses over at Udemy.

I really like ES6 and think it has a lot of great advantages, making life easier with Array helpers, fat arrows, and the ability to write less code in general.

Definitely spend some time learning ES 6 because it will help you understand other frameworks like React and Angular.

I have a loooooong way to go, but I really want to become a proficient programmer!

1 Like

I agree. It is fantastic to have so many resources but the lack of structure as well as the difficulty to know the quality of the resources beforehand makes us wander too much. That is one of the main reasons I am going through FCC, but not the only one.

Also, I have noticed that people do jump to libraries and frameworks at the first chance. It looks to me that many of them go more for the shortcuts than for the real learning, like if they were happy copy-pasting code as far as it works. I have a hard time working with things that I don´t understand.

Thank you very much for your advice about Udemy. I live you here some resources that I´ve found very useful when it comes to structure:

  1. A mind map of the things a web developer should know https://coggle.it/diagram/Vz9LvW8byvN0I38xist. The guy also has a video on youtube explaining the map which is worth watching.
  2. Things you should learn of ANY programming language: https://youtu.be/UFS7gi6LXhw
  3. The Net Ninja Series on you youtube. So simple that does not look much at the begging. What some episodes and you will start appreciating it. https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg
  4. Finally and mix of very good technical reflections and fun you have Funfunfunction by mpj. The guy may seem a little bit too histrionic but stick to the end of the first video and you will be hooked. https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q.

Cheers,

1 Like

Awesome!!! Thank you this is great :slight_smile: