Advertisement
beelzebielsk

stringsToNumber-low

Oct 27th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a function addThreeNumsFromString that takes a single string
  2.  * as argument. The given string will consist of three numbers
  3.  * separated by a space. The function will add the three the numbers
  4.  * and return their sum.
  5.  */
  6.  
  7. /* This is the low-level view of what's going on wrong: what
  8.  * operations are actually happening, what values are going into those
  9.  * operations and such.
  10.  */
  11.  
  12. /* The very first things that happen, before all the rest of your
  13.  * code:
  14.  * - All of your function definitions are "hoisted" to the top of your
  15.  *   program. Notice that you can call your functions earlier in your
  16.  *   code than the point at which you actually defined them. That's
  17.  *   not normal. Only JS really does this.
  18.  * - All of the variables that you defined with `var` are placed in
  19.  *   this global scope. If still foggy on what scope means, scope is
  20.  *   where names (variables) live. It's basically an object
  21.  *   (conceptually): names of variables are mapped to their values.
  22.  * - So, at this point in your program, the following names and values
  23.  *   are in scope:
  24.  *   - addThreeNumsFromString : function(str) {...}
  25.  *   - sum : undefined
  26.  *   - Any other JS objects like `console`, `Array`, `String`,
  27.  *     `Number`, and so on.
  28.  * - The reason that `sum` has a value of undefined is that variables
  29.  *   declared with `var` are given a sum of undefined to start until
  30.  *   the actual assignment statement you wrote happens. While the
  31.  *   names of variables declared with `var` are available at the start
  32.  *   of the scope in which they're defined, the values assinged to
  33.  *   them are not because the assignment statement hasn't happened
  34.  *   yet. This behavior is one of the reasons that many programmers
  35.  *   prefer `let` over `var`. You never have to account for this sort
  36.  *   of strange behavior.
  37.  */
  38.  
  39. console.log(addThreeNumsFromString("5 5 5"))
  40. // will log 15
  41. console.log(addThreeNumsFromString("4 2 1"))
  42. // will log 7
  43.  
  44.  
  45. //Your Answer:
  46. var sum = 0;
  47.  
  48. // For my explanations of this function, just assume that the argument
  49. // is the string "5 5 5".
  50. function addThreeNumsFromString (str){
  51.   /* Whenever you invoke `addThreeNumsFromString`, you open up a new
  52.    * scope as part of the function. This scope contains all of the
  53.    * parameters of your function, as bound to their actual arguments:
  54.    *    parameter Name : argument value
  55.    *    str            : "5 5 5"
  56.    * It also contains all of the names you declared with `var` inside
  57.    * of this function:
  58.    *    newArr         : undefined
  59.    *    i              : undefined
  60.    * Which start out at undefined because we have not yet gotten to
  61.    * the point in the function where the variables are assigned
  62.    * values.
  63.    */
  64.  
  65.   /* var newArr = str.split("");
  66.    * Evaluates to:
  67.    *    ['5', ' ', '5', ' ', '5']
  68.    */
  69.   var newArr = str.split("");
  70.   /* str.length is 5, because there's five characters in the string.
  71.    * You're going to iterate over the following values:
  72.    * i         : 0  , 1  , 2  , 3  , 4
  73.    * newArr[i] : '5', ' ', '5', ' ', '5'
  74.    */
  75.   for (var i = 0; i < str.length; i++){
  76.     /* - Adding is the right idea here.
  77.      * - Your inputs are wrong. The first thing that's wrong is that
  78.      *   you're trying to sum up *strings*, because you haven't
  79.      *   converted the strings into numbers.
  80.      *   - Desired behavior:
  81.      *      sum += Number(newArr[i])
  82.      *      sum = sum + Number(newArr[i])
  83.      *   - What was written:
  84.      *      sum += newArr[i]
  85.      *      sum = sum + newArr[i]
  86.      *      sum = String(sum) + newArr[i]
  87.      *   Because that's how JS handles addition with strings.
  88.      * - `sum` is also wrong here. You might expect `sum` to be 0, but
  89.      *   its not. At this point in your code, here's what your scope
  90.      *   looks like:
  91.      *      local scope:
  92.      *        str : "5 5 5"
  93.      *        newArr : ['5', ' ', '5', ' ', '5']
  94.      *        i : 0
  95.      *      enclosing scope (which is the global scope):
  96.      *        addThreeNumsFromString : function(str) {...}
  97.      *        sum : undefined
  98.      *        other JS global variables, like `console`, etc.
  99.      *   When you requiest the value of `sum`, JS will:
  100.      *   - Look in local scope first.
  101.      *   - See that there is no entry for `sum` in the local scope.
  102.      *   - Go to the enclosing scope, whatever that may be. In this
  103.      *     case it is the global scope.
  104.      *   - If `sum` is in this enclosing scope, then JS will take this
  105.      *     value.
  106.      *   - If `sum` is NOT in the global scope (which is the highest
  107.      *     scope), then you will get a ReferenceError.
  108.      *   - Since `sum` is in the global scope, the value of `sum` in
  109.      *     this scope would get used. Since you called the function
  110.      *     before `sum` got assigned value, value of `sum` is
  111.      *     `undefined`.
  112.      * - So, what actually gets executed on the first time this
  113.      *   statement happens (when i == 0):
  114.      *        sum += "5"
  115.      *        sum = sum               + "5"
  116.      *        sum = undefined         + "5"
  117.      *        sum = String(undefined) + "5"
  118.      *        sum = "undefined5"
  119.      *   because this is how JS is going to handle the addition of
  120.      *   these two values.
  121.      */
  122.     sum += newArr[i]
  123.   }
  124.   /* Consider that `sum` does not live inside of this function, but
  125.    * outside. Returning `sum` is the right idea, but it makes little
  126.    * sense when returned value lives outside of function's scope.
  127.    */
  128.   return sum;
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement