Wednesday, March 28, 2018

Javascript Variables

In C#, a method required you to declare the number of arguments and each arguments data type.If you declare a method requires an argument your code will not compile unless the argument is given each time the method is called. JavaScript works a little different.

JavaScript does not require you to specify the data types for each argument. It also does not perform any type of check on the arguments when the function is called. You can pass multiple arguments, or no arguments. If you declare an argument and the function receives nothing JavaScript will assume undefined for the missing arguments.

FreeCodeCamp had an algorithm where arguments were sent in different ways. For example, addTogether(2, 3) would return 5, just the sum of the two arguments passed.

 if(args.length == 2){
    if(typeof(args[0]) !== 'number' || typeof(args[1]) !=='number' ){
      return undefined;
      }
    return args[0]+args[1];
   }

But, what if you received something like addTogether(2)(3)? This confused me (and still kind of does), two sets of arguments? How do you deal with that?

I did some reading and found that it is a valid call to a function. Now I needed to figure out how to access that second variable.

It turns out that while looking at the first variable you can create another function that will look at the second variable.

if(args.length == 1){
     firstSet= args[0];
     
    if(typeof firstSet!=='number'){
        return undefined;
      }
   
    else{
       return function(secondSet){
         if(typeof secondSet !=='number'){
           return undefined;
           }
         else
            return firstSet+secondSet;
          };
      }
    }

Good to know, I'm just wondering when I will use this in real life...why would you send two sets of variables instead of just one set or an array?


"Sooner or later, those who win are those who think they can." - Paul Tournier


No comments: