Skip to content

Instantly share code, notes, and snippets.

@matt-winzer
Last active September 3, 2019 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-winzer/80387b714f5df66da737db867cca43a5 to your computer and use it in GitHub Desktop.
Save matt-winzer/80387b714f5df66da737db867cca43a5 to your computer and use it in GitHub Desktop.

Part I: Functions

Basic Requirements

  1. In your console, copy the following function and verify that the following invocations match your expectations:

    function square(num){
       return num * num;
    }
    
    square(10) + 2;
    square(100) + square(77);
    square(8 / 2)
    square(2 + 17);
    square(square(15));
  2. Write a sentence in plain English describing how square(square(15)) is evaluated.

    ANSWER: The inner function call square(15) is evaluated first, then its result is used to evaluate the outer function call.

  3. Rename square's num parameter in your above code to monkey, and rename the uses of that parameter in the body to monkey as well. Will the function square still work? Why or why not?

    ANSWER: The function square will still work, because the parameter monkey simply represents a placeholder for an actual value that is provided when the function is called. Thus, it does not need to be named semantically for the code to work.

  4. What is wrong with the following definitions of square? Write a sentence or two describing the issue(s); then, try copying the erroneous examples into a console one-at-a-time and observing the error(s) generated (you may have to attempt to invoke the functions to see the error). What errors are produced (if any) for each erroneous version? Do the errors make sense?

    function square(monkey) {
      return x * x;
    }

    PROBLEM: There is no reference to x available. The parameter monkey should be refactored to x or vice versa for the function to work.

    function square(5) {
      return 5 * 5;
    }

    PROBLEM: The number 5 cannot be used as a function parameter. Parameters must be placeholders/labels, not actual values.

    function square("x") {
      return "x" * "x";
    }

    PROBLEM: Similar to above, the string "x" cannot be used as a function parameter. Parameters must be placeholders/labels, not actual values. Also, strings cannot be multiplied together. The parameter should be refactored to x and the body of the function should be refactored to: return x * x;

  5. Fix the invalid syntax in the following functions (you can copy and paste these invalid definitions into your console and then edit them there):

    func square1(x {
      return x * x;
    }
    
    functionsquare2 x)
      return x * x;
    }
    
    function (x) square3 {
      return x * x;

    FIXED:

    function square1(x) {
      return x * x;
    }
    
    function square2(x) {
      return x * x;
    }
    
    function square3(x) {
      return x * x;
    }
  6. The following functions exhibit poor style -- fix these issues using the original version of square as a reference.

    function square(x){return x*x;}
    
    function square (x) { return x *x;
    }
    
    function square(x)
    {
    return x * x;
    }

    FIXED:

    function square(x) {
       return x * x;
    }
    
    function square(x) {
       return x * x;
    }
    
    function square(x) {
       return x * x;
    }
  7. Complete the function cube that returns the cube of x:

function cube(x) {
  // your code here
}

ANSWER:

function cube(x) {
  return x * x * x;
}

// OR

function cube(x) {
  return Math.pow(x, 3);
}
  1. Complete the function fullName that should take two parameters, firstName and lastName, and returns the firstName and lastName concatenated together with a space in between.

    // don't forget the parameters!
    function fullName() {
     // your code here
    }
    fullName("John", "Doe") // => "John Doe"

    ANSWER:

    function fullName(firstName, lastName) {
       return firstName + " " + lastName;
    }
  2. Write a function average that takes two numbers as input (parameters), and returns the average of those numbers.

    function average(num1, num2) {
       return (num1 + num2) / 2;
    }
  3. Write a function greeter that takes a name as an argument and greets that name by returning something along the lines of "Hello, <name>!"

function greeter(name) {
   return "Hello, " + name + "!";
}
  1. Using the document found at this link, translate the first page of geometric formulas into JavaScript functions.

    As an example, a function to compute the perimeter of a rectangle might look like this:

    function perimeterRect(l, w) {
      return 2 * (l + w);
    }

    NOTE: JavaScript provides some nifty mathematical functions and constants built into the language that you'll need for this exercise. The two that we'll be making use of are:

    Math.PI; // => 3.141592653589793
    Math.sqrt(256); // => 16

    To test your answers, you'll need to:

    1. Code your function in the console in the way that you think it will work
    2. Call the function with arguments in the console to see the result, e.g. perimeterRect(2, 6).
    3. Eventually, you may want to verify that the output is correct. Google is a great tool for this:

    google geometry answer

More Practice

Translate the rest of the geometric formulas found here into JavaScript functions.

Advanced (extra practice)

  1. Compound interest can be calculated with the formula:

    future value

    • F: future value
    • P: present value
    • i: nominal interest rate
    • n: compounding frequency
    • t: time

Write a function futureValue that can be used to calculate the future value of a quantity of money using compound interest.

Use the function to calculate what the future value of $1700 (P = 1700) deposited in a bank that pays an annual interest rate of 4.7% (i = 0.047), compounded quarterly (n = 4) after 6 years (t = 6) (you can use Math.pow to do exponentiation).

function futureValue(presentVal, interestRate, compoundingFreq, time) {
   return presentVal * Math.pow(1 + interestRate / compoundingFreq, compoundingFreq * time);
}

futureValue(1700, 0.047, 4, 6)    // => 2250.1218394891257
  1. Write a power function that accepts the parameters base and exponent and returns the result. Replace square and cube with the power function you just wrote. Do not use Math.pow.

    // Using Math.pow
    function power(base, exponent) {
       return Math.pow(base, exponent);
    }
    
    // Not using Math.pow
    function power(base, exponent) {
       var result = 1;
       for (var i = 0; i < exponent; i++) {
          result = result * base;
       }
       return result;
    }
  2. Write your own square-root function called sqrt that accepts a number parameter and returns an approximate square root. Square-root approximations make use of averages. Be sure to use the average function you previously wrote. The first version of your square root function should perform no more than 3 successive averages.

Part II: Booleans, Comparisons & Conditionals

Basic Requirements

Comparison Operators

  1. Type the two boolean values -- true and false -- into your console.

  2. Use the console to accomplish the following:

    • Write an expression using > that will evaluate to false
    • Write an expression using > that will evaluate to true
    • Write an expression using < that will evaluate to false
    • Write an expression using < that will evaluate to true
    • Write an expression using two numbers and === that will evaluate to true
    • Write an expression using two numbers and === that will evaluate to false
    • Write an expression using two strings and === that will evaluate to true
    • Write an expression using two strings and === that will evaluate to false
  3. Fill in the ??? with the following operators or values to make the statements output the expected Boolean value.

    12 ??? 78
    // => true
    
    24 ??? 16
    // => false
    
    45 !== ???
    // => true
    
    "45" ??? 45
    // => false
    
    "6" ??? "six"
    // => true

    POTENTIAL ANSWERS:

    12 < 78
    // => true
    
    24 > 16
    // => false
    
    45 !== 46
    // => true
    
    "45" === 45
    // => false
    
    "6" !== "six"
    // => true
  4. Write a function oldEnoughToDrink that takes an age as an argument and returns true if the person with that age is old enough to drink.

    function oldEnoughToDrink(age) {
      if (age >= 21) {
        return true;
      }
      return false;
    }
  5. There's an easy way to figure out how long a string is by adding .length to the end of it. Try this out in the console:

"hello".length;
"".length;
"John Doe".length;

Write a function sameLength that accepts two strings as arguments, and returns true if those strings have the same length, and false otherwise.

function sameLength(string1, string2) {
  if (string1.length === string2.length) {
    return true;
  }
  return false;
}
  1. Write a function passwordLongEnough that accepts a "password" as a parameter and returns true if that password is long enough -- you get to decide what constitutes long enough.

    function passwordLongEnough(password) {
      if (password.length >= 8) {
        return true;
      }
      return false;
    }

Conditionals: if

  1. Write a function bouncer that accepts a person's name and age as arguments, and returns either "Go home, NAME.", or "Welcome, NAME!" (where NAME is the parameter that represents the person's name) depending on whether or not the person is old enough to drink.

    function bouncer(name, age) {
      if (age >= 21) {
        return 'Welcome, ' + name + '!';
      }
      return 'Go home, ' + name + '.';
    }
  2. Write a function max that takes two numbers as arguments, and returns the larger one.

    function max(num1, num2) {
      if (num1 > num2) {
        return num1;
      }
      return num2;
    }
  3. Write a function min that takes two numbers as arguments, and returns the smaller one.

    function min(num1, num2) {
      if (num1 < num2) {
        return num1;
      }
      return num2;
    }
  4. Write functions larger and smaller that each accept two strings as arguments, and return the larger and smaller strings, respectively.

    function larger(string1, string2) {
      if (string1.length > string2.length) {
        return string1;
      }
      return string2;
    }
    
    function smaller(string1, string2) {
      if (string1.length < string2.length) {
        return string1;
      }
      return string2;
    }

More Practice

  1. Fill in the ??? with the following operators or values to make the statements output the expected Boolean value.

    106 ??? 12
    // => false
    
    "wiz" ??? "wiz"
    // => true
    
    7 * 7  ??? 49
    // => true
    
    12 ??? (24 / 2)
    // => false
    
    (20 % 2) <= ???
    // => true
    
    (9 / 3) + (5 * 5) === ???
    // => true

    POTENTIAL ANSWERS:

    106 <= 12
    // => false
    
    "wiz" === "wiz"
    // => true
    
    7 * 7  === 49
    // => true
    
    12 !== (24 / 2)
    // => false
    
    (20 % 2) <= 10
    // => true
    
    (9 / 3) + (5 * 5) === 28
    // => true
  2. Write the following functions that each accept a single number as an argument:

    • even: returns true if its argument is even, and false otherwise.
    function even(num) {
      // The number is even if it can be divided by 2 with no remainder
      if (num % 2 === 0) {
        return true;
      }
      return false;
    }
    • odd: the opposite of the above.
    function odd(num) {
      // The number is odd if it cannot be divided by 2 with no remainder
      if (num % 2 !== 0) {
        return true;
      }
      return false;
    }
    • positive: returns true if its argument is positive, and false otherwise.
    function positive(num) {
      if (num >= 0) {
        return true;
      }
      return false;
    }
    • negative: the opposite of the above.
    function negative(num) {
      if (num < 0) {
        return true;
      }
      return false;
    }
  3. A couple of other useful built-in mathematical functions are Math.random, Math.floor and Math.ceil. Look these functions up on MDN to learn how they work, and use them to implement the following functions:

    • randInt: Should accept a single numeric argument (n), and return a number from 0 to n.

      function randInt(n) {
        return Math.floor(Math.random() * (n + 1));
      }
    • guessMyNumber: Should accept a single numeric argument and compare it to a random number between 0 and 5. It should return one of the following strings:

      • "You guessed my number!" if the argument matches the random number.
      • "Nope! That wasn't it!" if the argument did not match the random number.
      function guessMyNumber(guess) {
         var randomNum = Math.floor(Math.random() * 6);
         if (guess === randomNum) {
           return "You guessed my number!";
         }
         return "Nope! That wasn't it!";
      }

Part III: Logical Operators & Advanced Conditionals

Basic Requirements

Logical Operators

  1. Is the ! operator a unary operator, or binary operator?

    ANSWER: It is a unary operator, because it has only one operand.

  2. Evaluate each of the following expressions first on a whiteboard, and then in a console:

    !(2 >= 2)      // => false
    !(4 === 4)     // => false
    !(5 !== 5)     // => true
  3. Evaluate each of the following expressions first on a whiteboard, and then in a console:

    1 > 2 || 2 > 2 || 3 > 2    // => true
    5 < 5 || 75 < 74           // => false

Conditionals: else if & else

  1. This guy named "Joe" keeps blacking out at the bar that your function, bouncer (from the previous module), is in charge of; thus, management has decided to add him to the "blacklist" -- modify the bouncer function from the previous section so that the person named "Joe" is rejected with an appropriate message, regardless of his age.

    function bouncer(name, age) {
      if (name === 'Joe') {
        return 'Go home, ' + name + '. You are banned from the bar.';
      } else if (age >= 21) {
        return 'Welcome, ' + name + '!';
      }
      return 'Go home, ' + name + '.';
    }
  2. Write a function called scoreToGrade that accepts a number as a parameter and returns a string representing a letter grade corresponding to that score.

    For example, the following grades should be returned given these scores:

    • 'A' >= 90
    • 'B' >= 80
    • 'C' >= 70
    • 'D' >= 60
    • 'F' < 60
    function scoreToGrade(score) {
      if (score >= 90) {
        return 'A';
      } else if (score >= 80) {
        return 'B';
      } else if (score >= 70) {
        return 'C';
      } else if (score >= 60) {
        return 'D';
      } else {
        return 'F';
      }
    }
    scoreToGrade(95); // => 'A'
    scoreToGrade(72); // => 'C'
  3. Modify the scoreToGrade function so that it returns 'INVALID SCORE' if the score is greater than 100 or less than 0.

    function scoreToGrade(score) {
      if (score > 100 || score < 0) {
        return 'INVALID SCORE';
      } else if (score >= 90) {
        return 'A';
      } else if (score >= 80) {
        return 'B';
      } else if (score >= 70) {
        return 'C';
      } else if (score >= 60) {
        return 'D';
      } else {
        return 'F';
      }
    }

More Practice

  1. Think of at least three activities that you enjoy doing outdoors and the range of temperatures and weather patterns (e.g sunny, windy, snowy, rainy, etc.) that are best for these activities. Write a function whatToDoOutside that accepts a temperature and condition as parameters and outputs a string of the format: "The weather is ideal for: ACTIVITY" (where ACTIVITY is an actual activity). Make sure to include an else that indicates what should be done if the conditions do not match any activities. If you're short on inspiration, here are some ideas:

    • Snow Sports: snowboarding, skiing
    • Water Sports: surfing, sailing, paddle boarding, swimming
    • Team Sports: basketball, baseball, football (American or everywhere else), etc.
    function whatToDoOutside(temperature, condition) {
      var activity = '';
      
      if (temperature >= 80 && condition === 'sunny') {
        activity = 'swimming';
      } else if (temperature >= 80 && condition === 'windy') {
        activity = 'sailing';
      } else if (temperature >= 60 && condition === 'sunny') {
        activity = 'basketball';
      } else if (temperature >= 60 && condition === 'windy') {
        activity = 'hiking';
      } else if (temperature < 60 && condition === 'snowy') {
        activity = 'skiing';
      } else {
        activity = 'building a bonfire';
      }
      
      return 'The weather is ideal for: ' + activity + '.';
    }
  2. The guessMyNumber function from the Booleans & Conditionals module (More Practice section) accepts a guess n and checks it against a random number from 0 to 5 -- if the guess n is greater than 5, output a different message indicating that the guess is out of bounds.

    • NOTE: It will be helpful to first write a randInt function that accepts a number n and computes a random integer from 0 to n; then, you can use this function in guessMyNumber.

      function randInt(n) {
        return Math.floor(Math.random() * (n + 1));
      }
      
      function guessMyNumber(n) {
         var randomNum = randInt(5);
         
         if (n > 5) {
           return "Your guess is out bounds."
         } else if (n === randomNum) {
           return "You guessed my number!";
         }
         return "Nope! That wasn't it!";
      }
  3. Modify the scoreToGrade function so that it returns 'A+/A-' for scores of 98-100/90-92 respectively. Apply the same logic for all other letter grades.

    function scoreToGrade(score) {
      if (score > 100 || score < 0) {
        return 'INVALID SCORE';
      } else if (score >= 98) {
        return 'A+';
      } else if (score >= 93) {
        return 'A';
      } else if (score >= 90) {
        return 'A-';
      } else if (score >= 88) {
        return 'B+';
      } else if (score >= 83) {
        return 'B';
      } else if (score >= 80) {
        return 'B-';
      } else if (score >= 78) {
        return 'C+';
      } else if (score >= 73) {
        return 'C';
      } else if (score >= 70) {
        return 'C-';
      } else if (score >= 68) {
        return 'D+';
      } else if (score >= 63) {
        return 'D';
      } else if (score >= 60) {
        return 'D-';
      } else {
        return 'F';
      }
    }

Advanced

  1. The bar that employs our bouncer function has decided to do live music on Friday and Saturday nights, and will be admitting those that are over 18 to the bar on those nights; the catch however, is that all who are 21 or older will need to be given a wristband to distinguish them from the minors. Modify your bouncer function to handle this situation.

    function bouncer(name, age, day) {
      if (name === 'Joe') {
        return 'Go home, ' + name + '. You are banned from the bar.';
      } else if ((day === 'Friday' || day === 'Saturday') && age >= 21) {
        return 'Welcome, ' + name + '! Here is your wristband.'
      } else if ((day === 'Friday' || day === 'Saturday') && age >= 18) {
        return 'Welcome, ' + name + '! You can come in but no drinking.'
      } else if (age >= 21) {
        return 'Welcome, ' + name + '!';
      }
      return 'Go home, ' + name + '.';
    }
  2. You should have noticed a large amount of repetitive code when modifying scoreToGrade to accommodate + or - grades. When we do lots of repetitive things, that's a clear signal that there's a better way. Write a helper function letterGrade that accepts two arguments, letter and score, and works as follows:

    function letterGrade(letter, score) {
      if (score % 10 >= 8) {
        return letter + '+';
      } else if (score % 10 >= 3) {
        return letter;
      } else {
        return letter + '-';
      }
    }
    
    // These are examples of what a *working* function would output.
    letterGrade('A', 95); // => 'A'
    letterGrade('A', 91); // => 'A-'
    letterGrade('B', 88); // => 'B+'
    letterGrade('monkey', 160); // => 'monkey-'

    Finally, use letterGrade to remove the repetition in scoreToGrade.

    function scoreToGrade(score) {
      if (score > 100 || score < 0) {
        return 'INVALID SCORE';
      } else if (score === 100) {
        return 'A+';
      } else if (score >= 90) {
        return letterGrade('A', score);
      } else if (score >= 80) {
        return letterGrade('B', score);
      } else if (score >= 70) {
        return letterGrade('C', score);
      } else if (score >= 60) {
        return letterGrade('D', score);
      } else {
        return 'F';
      }
    }
  3. It turns out that we can write logical and and logical or in terms of each other and logical not using De Morgan's Laws.

    • Write a function or that works like ||, but only uses ! and &&.
    function or(a, b) {
      return !(!a && !b);
    }
    
    or(true, false);    // => true
    or(true, true);     // => true
    or(false, false);   // => false
    • Write a function and that works like &&, but only uses ! and ||.
    function and(a, b) {
      return !(!a || !b);
    }
    
    and(true, false);   // => false
    and(true, true);    // => true
    and(false, false);  // => false

Part IV: Arrays

Basic Requirements

Creating Arrays

  1. Using the array: ["cat", "fox", "dog", "monkey"], what is the index of:

    • "dog"? // => 2
    • "monkey"? // => 3
    • "cat"? // => 0
  2. Fix the syntax/style in the following arrays:

[ 1, 3 4 7,9, ]
"the""quick""brown","fox" "jumped","over" the lazy, "dog",  ]
[true false,true

FIXED:

[1, 3, 4, 7, 9]
["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
[true, false, true]
  1. Create arrays in the global scope of your program consisting of strings that represent:

    • Your favorite TV shows/movies
    • Names of people you know/care about
    • Favorite sports/activities

Accessing Array Elements

  1. Using the arrays that you created in the last exercise, use the console to access:

    • First elements,
    • Last elements,
    • Other elements!
  2. Write a function first that takes an array as an argument and returns the first element in that array.

    function first(arr) {
      return arr[0];
    }
  3. Write a function last that takes an array as an argument and returns the last element in the array. Hint: What is the relationship between the index of the last element in the array and the length of the array?

    function last(arr) {
      var lastIndex = arr.length - 1; 
      return arr[lastIndex];
    }

Modifying Arrays

  1. Using push and unshift, make this array contain the numbers from zero through seven:

    var arr = [2, 3, 4];
    
    arr.unshift(1);
    arr.unshift(0);
    arr.push(5);
    arr.push(6);
    arr.push(7);
    
    arr; // => [0, 1, 2, 3, 4, 5, 6, 7]
  2. What is returned by push? Before throwing this into the console, form a hypothesis about what you think the return value will be:

    var arr = [5, 7, 9];
    arr.push(6); // => ???

    Were you correct? What is the returned by push? Does unshift work in the same way?

    ANSWER: Both .push() and .unshift() return the length of the new array.

  3. We can use the assignment operator (=) to replace elements in arrays with other ones like so:

    var animals = ['dog', 'elephant', 'zebra']
    // let's replace 'dog' with 'hippo'
    animals[0] = 'hippo';
    animals; // => ['hippo', 'elephant', 'zebra']

    Using the same principle, perform the following:

    // 1. Change all odd numbers to be those numbers multiplied by two:
    var numbers = [4, 9, 7, 2, 1, 8];
    
    numbers[1] = numbers[1] * 2;
    numbers[2] = numbers[2] * 2;
    numbers[4] = numbers[4] * 2;
    
    numbers; // => [4, 18, 14, 2, 2, 8]
    
    // 2. Fix the typos by replacing each element with a correctly spelled version
    var places = ['snfranisco', 'oacklannd', 'santacrus']
    
    places[0] = 'san francisco';
    places[1] = 'oakland';
    places[2] = 'santa cruz';
    
    places; // => ['san francisco', 'oakland', 'santa cruz']

More Practice

  1. Write a function called nth that accepts an array and an index as parameters, and returns the element at that index.

    function nth(array, index) {
      return array[index];
    }
    var animals = ['dog', 'cat', 'gerbil'];
    nth(animals, 2); // => 'gerbil'
    nth(animals, 1) === animals[1]; // => true
  2. Write a function rest that returns all the elements in the array except for the first one. HINT: Read about the slice method on MDN and/or experiment with slice at the console like so:

    var numbers = [3, 2, 7, 5];
    numbers.slice(0);
    numbers.slice(1);
    numbers.slice(2);
    numbers.slice(0, 2);
    function rest(arr) {
      return arr.slice(1);
    }
  3. Write a function butlast that returns all of the elements in the array except for the last one (you may want to use slice for this one as well).

    function butlast(arr) {
      return arr.slice(0, -1);
    }
  4. Complete the function cons that accepts an element and an array, and returns an array with the element added to the front of the array:

    function cons(x, array) {
      array.unshift(x);
      return array;
    }
  5. Complete the function conj that accepts an array and an element, and returns an array with the element added to the end of the array:

    function conj(array, x) {
      array.push(x);
      return array;
    }
  6. What benefit(s) might there be to using functions like cons or conj over unshift or push?

    ANSWER: The array that we are modifying is being returned to us when we use these functions, whereas .unshift() and .push() return the array's new length. It is often the case that we want to perform addition operations using the array after it has been modified; using these functions makes doing so easier.

  7. Try the following in a console:

    var arr = [];
    arr[7] = "Hello."
    arr; // => ???

    What is the value of arr after assigning an element to its seventh index? Explain the result in plain English.

    ANSWER: The value of arr is an array with the following characteristics:

    • Length of 8
    • Contains 7 empty elements (indices 0-6)
    • Contains the string "Hello." as its 8th element (index 7) In order to assign a value at index 7 (arr[7] = "Hello.") JavaScript has inserted empty elements at all preceding indices. It may help to think of arrays like a collection of boxes in which we can store values, with each box representing an element at a given index. In order to have a value in our 8th box (arr[7]), we must have the other boxes that came before it, even if they are empty.

Advanced

  1. Without running the below function, use a whiteboard to figure out what it should return by repeatedly expanding function invocations:

    function mystery(array) {
      if (array.length === 0) {
        return [];
      }
      return conj(mystery(rest(array)), first(array));
    }
  2. Using first, rest, conj and/or cons, write functions that accomplish the following:

    function first(arr) {
      return arr[0];
    }
    
    function rest(arr) {
      return arr.slice(1);
    }
    
    function cons(x, array) {
      array.unshift(x);
      return array;
    }
    
    function conj(array, x) {
      array.push(x);
      return array;
    }
    • sum all the elements of an array
    function sumArray(arr) {
       var sum = 0;
       
       while (arr.length > 0) {
         sum = sum + first(arr);
         arr = rest(arr);
       }
       
       return sum;
    }
    • Given an array, returns a new array with each element squared
    function squaredArray(arr) {
      var squaredArr = [];
      
      while (arr.length > 0) {
        var squaredNum = first(arr) * first(arr);
        conj(squaredArr, squaredNum);
        arr = rest(arr);
      }
      
      return squaredArr;
    }
    • Given an array of numbers, returns a new array of just the even numbers
    function evenArray(arr) {
      var evenArr = [];
      
      while (arr.length > 0) {
        var current = first(arr);
        if (current % 2 === 0) {
          conj(evenArr, current);
        }
        arr = rest(arr);
      }
      
      return evenArr;
    }

    HINT: After figuring out how the mystery function works above, use it as a reference for how to write this type of function.

Part V: Array Iteration

Before getting started, make sure that you have a JavaScript console open (like repl.it), so you can complete these exercises.

Exercises

Try to write all of the exercises using both the for loop and while loop.

Basic Requirements

  1. Write a function sum that computes the sum of the numbers in an array.
function sumFor(nums) {
  var total = 0;
  for (var i = 0; i < nums.length; i = i + 1) {
    total = total + nums[i];
  }
  return total;
}

function sumWhile(nums) {
  var total = 0;
  var i = 0;
  while (i < nums.length) {
    total = total + nums[i];
    i = i + 1;
  }
  return total;
}
  1. Write a function max that accepts an array of numbers and returns the largest number in the array.
function maxFor(nums) {
  var largest = nums[0];
  for (var i = 0; i < nums.length; i = i + 1) {
    if (nums[i] > largest) {
      largest = nums[i];
    }
  }
  return largest;
}

function maxWhile(nums) {
  var largest = nums[0];
  var i = 0;
  while (i < nums.length) {
    if (nums[i] > largest) {
      largest = nums[i];
    }
    i = i + 1;
  }
  return largest;
}
  1. Try the following at a console:
"the quick brown fox jumped over the lazy dog".split(" ");
"Hello, world!".split("")
"1,2,3,4,5,6".split(",")

What is returned by split (You can read more about it here), and how does it work?

ANSWER: The split() method splits a string into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split. This separator string is the argument passed to .split(). The return value is the array of substrings.

Use split to write a function longestWord that takes a string as an argument and returns the longest word.

function longestWordFor(str) {
  var split = str.split(' ');
  var longest = split[0];
  for (var i = 0; i < split.length; i = i + 1) {
    if (split[i].length > longest.length) {
      longest = split[i];
    }
  }
  return longest;
}
longestWordFor('all your base are belong to us') // => 'belong';

function longestWordWhile(str) {
  var split = str.split(' ');
  var longest = split[0];
  var i = 0;
  while (i < split.length) {
    if (split[i].length > longest.length) {
      longest = split[i];
    }
    i = i + 1;
  }
  return longest;
}
longestWordWhile('all your base are belong to us') // => 'belong';
  1. Write a function remove that accepts an array and an element, and returns an array with all ocurrences of element removed.
function removeFor(array, element) {
 var removed = [];
 for (var i = 0; i < array.length; i = i + 1) {
   if (array[i] !== element) {
     removed.push(array[i]);
   }
 }
 return removed;
}
removeFor([1, 3, 6, 2, 3], 3); // => [1, 6, 2]

function removeWhile(array, element) {
var removed = [];
var i = 0;
while (i < array.length) {
  if (array[i] !== element) {
     removed.push(array[i]);
   }
   i = i + 1;
}
return removed;
}
removeWhile([1, 3, 6, 2, 3], 3); // => [1, 6, 2]
  1. Write a function evens that accepts an array as an argument, and returns an array consisting of all of the even numbers in that array.
function evensFor(array) {
  var evenNums = [];
  for (var i = 0; i < array.length; i = i + 1) {
    if (array[i] % 2 === 0) {
      evenNums.push(array[i]);
    }
  }
  return evenNums;
}
evensFor([1, 2, 3, 4, 5, 6, 7, 8]) // => [2, 4, 6, 8];

function evensWhile(array) {
  var evenNums = [];
  var i = 0;
  while (i < array.length) {
    if (array[i] % 2 === 0) {
      evenNums.push(array[i]);
    }
    i = i + 1;
  }
  return evenNums;
}
evensWhile([1, 2, 3, 4, 5, 6, 7, 8]) // => [2, 4, 6, 8];

More Practice

  1. Write a function called average that takes an array of numbers as a parameter and returns the average of those numbers.
function averageFor(array) {
  var result = 0;
  for (var i = 0; i < array.length; i = i + 1) {
    result = result + array[i];
  }
  return result / array.length;
}
averageFor([1, 2, 3, 4, 5]) // => 3;

function averageWhile(array) {
  var result = 0;
  var i = 0;
  while (i < array.length) {
    result = result + array[i];
    i = i + 1;
  }
  return result / array.length;
}
averageWhile([1, 2, 3, 4, 5]) // => 3;
  1. Write a function called min that finds the smallest number in an array of numbers.
function minFor(array) {
  var min = array[0];
  for (var i = 0; i < array.length; i++) {
    if (array[i] < min) {
      min = array[i];
    }
  }
  return min;
}
minFor([10, 12, 5, 15, 20]) // => 5;

function minWhile(array) {
  var min = array[0];
  var i = 0;
  while (i < array.length) {
    if (array[i] < min) {
      min = array[i];
    }
    i = i + 1;
  }
  return min;
}
minWhile([10, 12, 5, 15, 20]) // => 5;
  1. Write a function shortestWord that works like longestWord, but returns the shortest word instead.
function shortestWordFor(str) {
  var split = str.split(' ');
  var shortest = split[0];
  for (var i = 0; i < split.length; i = i + 1) {
    if (split[i].length < shortest.length) {
      shortest = split[i];
    }
  }
  return shortest;
}
shortestWordFor('all your base are belong to us') // => 'to';

function shortestWordWhile(str) {
  var split = str.split(' ');
  var shortest = split[0];
  var i = 0;
  while (i < split.length) {
    if (split[i].length < shortest.length) {
      shortest = split[i];
    }
    i = i + 1;
  }
  return shortest;
}
shortestWordWhile('all your base are belong to us') // => 'to';
  1. Write a function countChar that takes two arguments: any string, and a character (string of one letter), and returns the number of times that the character occurs in the string.
function countCharFor(str, char) {
  var occurances = 0;
  for (var i = 0; i < str.length; i = i + 1) {
    if (str[i] === char) {
      occurances = occurances + 1;
    }
  }
  return occurances;
}
countCharFor('hello world', 'o') // => 2;

function countCharWhile(str, char) {
  var occurances = 0;
  var i = 0;
  while (i < str.length) {
    if (str[i] === char) {
      occurances = occurances + 1;
    }
    i = i + 1;
  }
  return occurances;
}
countCharWhile('hello world', 'o') // => 2;
  1. Write a function evenLengthWords that takes an array of strings as an argument, and returns an array of just the words that have an even length.
function evenLengthWordsFor(strings) {
  var result = [];
  for (var i = 0; i < strings.length; i = i + 1) {
    if (strings[i].length % 2 === 0) {
      result.push(strings[i]);
    }
  }
  return result;
}
evenLengthWordsFor(['hello', 'world', 'I', 'am', 'here']) // => ['am', 'here'];

function evenLengthWordsWhile(strings) {
  var result = [];
  var i = 0;
  while (i < strings.length) {
    if (strings[i].length % 2 === 0) {
      result.push(strings[i]);
    }
    i = i + 1;
  }
  return result;
}
evenLengthWordsWhile(['hello', 'world', 'I', 'am', 'here']) // => ['am', 'here'];

Advanced

  1. Read about the join method on MDN and use it to implement a function that accepts a string as an argument and returns that string reversed.
function reverseString(str) {
  return str.split('').reverse().join('');
}
reverseString('hello') // => 'olleh';
  1. Write a function keep that "keeps" certain elements in an array. The function will need to take two arguments, an array, and something else -- the second argument will be what is used to determine which elements to keep.
function keep(array, fn) {
  var result = [];
  for (var i = 0; i < array.length; i = i + 1) {
    if (fn(array[i]) === true) {
      result.push(array[i]);
    }
  }
  return result;
}

You should be able to use this function to write evens, evenLengthWords, a hypothetical odds function, or oddLengthWords without changing the keep function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment