JavaScript Exercises

Here is a collection of exercises usable for homework assignments, in class discussions, or exams.

  1. Match the terms with their definitions, by writing the letter of the definition next to the term.
    1. Expression _______
    2. Variable _______
    3. Statement _______
    4. || _______
    5. Function _______
    6. Loop _______
    7. Exception _______
    8. Argument _______
    9. % _______
    10. Applet _______
    11. Enum _______
    12. Codepoint _______
    13. Boolean _______
    14. Context _______
    15. Computing _______
    1. An object that you throw to signal that something is wrong
    2. The primitive type containing only the values true and false.
    3. The science of information processes
    4. A named storage location
    5. The "or-else" operator
    6. A user-defined type containing a fixed number of elements
    7. A JavaScript object used for drawing in a canvas
    8. The mathematical remainder operator
    9. A parameterized chunk of code that can be run
    10. A program designed to run inside of another (often a web browser)
    11. A chunk of code that is evaluated
    12. Code that produces an action
    13. Code that is executed repeatedly
    14. A value passed to a function
    15. The position of a character within a character set
  2. Show the fully-parenthesized form of each of the following expressions:
    1. 1 - 2 - (3 - 4 - 5) - 6
    2. ! x && y && z
    3. a < b > c == d > e
    4. typeof + 3
  3. Write a script that prompts for the mass of an object in kilograms and alerts a nice message stating its energy content in petajoules. Use the formula E=mc2, where E is the energy content (in joules), m is the mass (in kilograms), and c is 299,792,458 m/s. By the way, a petajoule is one quadrillion (1015) joules.
  4. Is first-guess a legal variable name in JavaScript? If not, why do you think such a name was banned? (Answer using complete sentences. Back up your answer. Concrete examples will most likely be helpful.)
  5. Here is a script that determines how long it takes to grow $1000 into $5000 assuming an APR (annual percentage rate) of 5%, compounded yearly:
    var total = 1000;
    var year = 0;
    while (total < 5000) {
        year = year + 1;
        total = total * 1.05;
    }
    alert("It will take you " + year + " years to get there.");
    

    Modify the script so that it first prompts for the APR and then computes the amount of time required to grow the $1000 to $5000 where the rate is compounded monthly. You may alert the result in either months or years.

  6. Write an expression that is true if and only if the value stored in variable x is between 0 and 10 (inclusive).
  7. Write a script that prompts for a string, then alerts whether or not the entered string contains either a backslash character or a Telugu letter ddha (U+0C22). You should use the indexOf operator on strings. Recall that s.indexof(t) will return the first position (starting at 0) at which t appears, but returns a negative number if t is not found within s.
  8. Evaluate the expression "dog".charAt(2).charAt(0) and explain the result.
  9. Write a script that prompts for the abbreviation of a New England state and alerts the capital of that state. The first line is:
    var capitals = {ME: "Augusta", NH: "Concord", VT: "Montpelier", MA: "Boston",
        CT: "Hartford", RI: "Providence"};
    
    Therefore, if your user inputs NH, your script should alert Concord. If you want a point of extra credit, allow the user to enter data in any case, for example NH, Nh, nH, or nh for New Hampshire.
  10. Draw a picture of the objects resulting from the following declaration:
    var p1 = {name: "Alice"};
    var p2 = {name: "Bob", manager: p1};
    p1.manager = p1;
    
    What is the value of p2.manager.manager.manager.name?
  11. Draw a picture of the array referred to by the variable a after executing the following:
    var a = [1,2,3,4]; a.unshift(a.pop()); a.concat([5, 6, 7]);
    
  12. Define a prototype guitar and three guitars based on that prototype as follows:
  13. Draw a picture representing the following collection of variables and their values:
    var character = {real: true, gender: "female"};
    var alice = Object.create(character);
    alice.name = "Alice";
    alice.next = Object.create(character);
    alice.next.name = "Tweedledee";
    alice.next.real = false;
    alice.next.gender = "male";
    alice.next.next = Object.create(character);
    alice.next.next.real = false;
    alice.next.next.name = "Red Queen";
    alice.next.next.next = alice;
    
  14. Write a script that prompts for two strings and then alerts whether one string is a substring of the other. Do not use an if statement.
  15. Write a script that reads the content of the HTML textbox with the ID of "message" and then writes into the HTML element with ID "shuffled" the value of the original string with its two halves swapped. Here are several examples of swapping halves:
        ""  ⇒  ""
        "it"  ⇒  "ti"
        "lizard"  ⇒  "ardliz"
        "this laptop is lame"  ⇒  "op is lamethis lapt"
    
  16. Write a JavaScript function called dollarMessage that has one parameter representing a number of dollars and returns a string stating how many dollars this is. Here are some test cases:
        dollarMessage(5) ⇒ "5 dollars"
        dollarMessage(1) ⇒ "1 dollar"
        dollarMessage(7.244) ⇒ "7.244 dollars"
    
    Use a conditional expression, not an if-statement, to distinguish between writing "dollar" versus "dollars".
  17. Write a JavaScript function called isNonnegativeAndFinite that takes a single parameter and returns whether or not its value, when interpreted as a number, is nonnegative and finite.
  18. Write a function called sign that takes one parameter, a number, and returns -1 if the number is negative, 0 if the number is 0, 1 if the number is positive, and NaN if the parameter is not a number. Use an if-statement.
  19. Write a function called isSmallInteger which returns true if its sole parameter is an integer between -128 and 127, inclusive, and false otherwise. Your function body should have a single return statement in which you test that your parameter is not NaN, not a floating point number (you can use the remainder when divided by 1 idiom), greater than or equal to -128 and less than or equal to 127.
        isSmallInteger("dog") ⇒ false
        isSmallInteger(-129) ⇒ false
        isSmallInteger(-128) ⇒ true
        isSmallInteger(127) ⇒ true
        isSmallInteger(128) ⇒ false
        isSmallInteger(14.8) ⇒ false
        isSmallInteger(14.0) ⇒ true
    
  20. Write a function called sumOfRange that takes in two parameters, x and y, which should both be small integers (see the previous problem), and returns the sum of all of the integers in the range from x (inclusive) to y (exclusive). If either of x or y is not a small integer (call the function from the previous problem to check this!!!) then throw an exception. Example test cases for you:
        sumOfRange(5, 9) ⇒ 5 + 6 + 7 + 8 = 26
        sumOfRange(-2, 4) ⇒ -2 + -1 + 0 + 1 + 2 + 3 = 3
        sumOfRange(9, 5) ⇒ 0 (because there are no numbers >=9 AND <5)
        sumOfRange(-99999, 0) ⇒ throws an exception
        sumOfRange(14, "dog") ⇒ throws an exception
    
  21. Write a function called sumOfEvensInRange that takes in two parameters, x and y, which should both be short integers (see the previous problem), and returns the sum of all of the even integers in the range from x (inclusive) to y (exclusive). If either of x or y is not a short integer (call the function from the previous problem to check this!!!) then throw an exception. Example test cases for you:
        sumOfEvensInRange(5, 9) ⇒ 6 + 8 = 14
        sumOfEvensInRange(-2, 4) ⇒ -2 + 0 + 2 = 0
        sumOfEvensInRange(9, 5) ⇒ 0 (because there are no numbers >=9 AND <5)
        sumOfEvensInRange(-99999, 0) ⇒ throws an exception
        sumOfEvensInRange(14, "dog") ⇒ throws an exception
    
  22. Write a function called sumOfCodepoints which takes a string and returns the sum of each of the codepoints in the string.
  23. Write a function with no parameters that returns a two-element array containing two (possibly different) dice rolls.
  24. Write a function that returns a two-element array containing two (possibly different) dice rolls for an N-sided die. You should read the phrase "N-sided" die as implying that N should be a parameter of your function.
  25. Write a function called withoutMiddleThird which takes a string and returns the string that is like its argument but without its "middle third" characters. Examples:
        withoutMiddleThird("ABCDEFGHI") ⇒ "ABCGHI"
        withoutMiddleThird("") ⇒ ""
        withoutMiddleThird("a") ⇒ "a"
        withoutMiddleThird("ab") ⇒ "b"
        withoutMiddleThird("abc") ⇒ "ac"
    
  26. Write a function called squares that takes in an array and returns a NEW array containing all the squares of the input array. Test cases:
        squares([1,7,-4]) ⇒ [1,49,16]
        squares([]) ⇒ []
        squares([true, -6, null]) ⇒ [1, 36, 0]
    
  27. Write a function called square that takes in an array of numbers and CHANGES THIS ARRAY by replacing each element with its square. Test cases:
        var a = [1,7,-4];
        square(a);
        a ⇒ [1,49,16]
    
  28. Write a function called chomped that takes in an array and returns a NEW array containing all the values of the input array, interpreted as strings, with their last characters removed. Test cases:
        chomped(["one", "two", "three"]) ⇒ ["on", "tw", "thre"]
        chomped([]) ⇒ []
        chomped([true, -6, null]) ⇒ ["tru", "-", "nul"]
    
  29. Write a function called chompAll that takes in an array and CHANGES THIS ARRAY by replacing each element with its chompedness. The description of chomping can be gleaned from reading the description in the previous problem. Test cases:
        var a = ["one", "two", "three"];
        chompAll(a);
        a ⇒ ["on", "tw", "thre"]
    
  30. Write a function that takes in one parameter and returns how many times you have to cut it in half to produce a value less than or equal to 1. Note that if the number is already 1 or less, you should immediately return 0. Use a while statement or a do-while statement. Some test cases for you:
        halfsies(1) ⇒ 0
        halfsies(0) ⇒ 0
        halfsies(-22.7) ⇒ 0
        halfsies(2) ⇒ 1
        halfsies(19) ⇒ 5
        halfsies(7.225E102) ⇒ 342
    
  31. You're working with a team of programmers and you need a factorial function. (The factorial of a positive integer n is the product 1 * 2 * ... * n, with the factorial of all values less than or equal to 1 being taken as 1.) Someone on your team gives you this:
    var product = 1;
    // Returns the factorial of n.  Precondition: n is a positive
    // integer <= 18.
    var factorial = function (n) {
        for (var i = 2; i <= n; i += 1) {
            product *= i;
        }
        return product;
    }
    
    Naturally, you are extremely disappointed in your co-worker's solution. Why is it so bad? (For full credit, don't just say "Because it doesn't work." Give an explanation that shows you understand the defect in the code.)
  32. What is alerted in the following script and why?
    var x = 20;
    var f = function (y) {alert(x / y); y = 3;}
    f(8);
    alert(y);
    
  33. Here is an attempt to write a script that computes the sum of the numbers from 1 to 10000, inclusive. However, there are three major problems. Identify the mistakes and explain how to correct them. (Note: find actual programming mistakes, not mistakes of style; do not pick on the names, the indentation, the formatting, or the lack of comments.)
    var sum;
    for (int i = 1; i < 10000; i++) {
        sum += i;
        alert("The sum from 1 to 10000 is " + sum);
    }
    
  34. Write a script that asks the user for a string via prompt, then displays the Fuddified version of the string with alert. (The Fuddified version of a string is the string with all r's and l's replaced with w's.)
  35. Write a function that accepts a non-negative integer between 1 and 10000 inclusive and returns the length of the Collatz sequence starting at that value. Throw an exception if the argument isn't desirable.
        lengthOfCollatzSequence(1) ⇒ 1
        lengthOfCollatzSequence(3) ⇒ 8
        lengthOfCollatzSequence(4) ⇒ 3
        lengthOfCollatzSequence(16) ⇒ 5
    
  36. Write a function to determine whether a given year is a leap year or not. Throw an exception if the year is earlier than 1582. Note: A year is a leap year if it is divisible by 4, but not 100, unless also by 400.
        isLeapYear(2000) ⇒ true
        isLeapYear(1940) ⇒ true
        isLeapYear(2100) ⇒ false
        isLeapYear(1987) ⇒ false
        isLeapYear(1381) ⇒ (throws an exception)
    
  37. Write a function that takes in an object with an x property and a y property, and returns the quadrant of the point. In case you didn't know, Quadrant 1 contains points with non-negative x and non-negative y; quadrant 2 has points with negative x and non-negative y; in quadrant three both x and y are negative; quadrant 4 has non-negative x and negative y.
  38. Write a function that takes in a string s and returns the string which is equivalent to s but with all ASCII vowels removed. (ASCII characters are those Unicode characters whose codepoints are in the range 0..127 inclusive.)
        stripVowels("Hello, world") ⇒ "Hll, wrld"
    
  39. Write a function that randomly permutes a string. By random we mean that each time you call the method for a given argument all possible permutations are equally likely (note that "random" is not the same as "arbitrary.") For example:
        scramble("Hello, world") ⇒ "w,dlroH elol"
    
  40. Write a function that produces powers of two starting at 1 and going up to some limit.
        powersOfTwo(70) ⇒ [1,2,4,8,16,32,64]
    
  41. What is alerted in the following script?
    var x = 1;
    var f = function (y) {alert(x + y);}
    f(2);
    
    What would happen if the parameter y were renamed to x?
  42. Write a function that doubles up each item in an array. Here are test cases your function should satisfy:
        stutter([5,true,[3],"ha"]) ⇒ [5,5,true,true,[3],[3],"ha","ha"]
        stutter([{}, null]) ⇒ [{}, {}, null, null]
    
  43. Write a function that takes in a point object, that is, an object with an x property and a y property, and returns the quadrant of the point. In case you didn't know, Quadrant 1 contains points with non-negative x and non-negative y; quadrant 2 has points with negative x and non-negative y; in quadrant three both x and y are negative; quadrant 4 has non-negative x and negative y.
  44. Write a script that produces an array with successive prefixes of argument, starting with the first prefix, which is zero characters long. For example:
        prefixes("eich") ⇒ ["", "e", "ei", "eic", "eich"]
        prefixes("") ⇒ [""]
    
  45. Write a function that produces an array with successive suffixes of its argument, starting with the first suffix, which is zero characters long. For example:
        suffixes("eich") ⇒ ["", "h", "ch", "ich", "eich"]
        suffixes("") ⇒ [""]
    
  46. Write a function that removes "every nth character" of string. That is, given a string s and a positive integer n return the string like s but with characters at positions 0, n, 2n, 3n, and so on, removed. Throw an exception if n is not a positive integer.
        sift("javascript", 2) ⇒ "aacit"
        sift("python", -4) ⇒ throws an exception
        sift("coffeescript", 5) ⇒ "offescrit"
        sift("java", alert) ⇒ throws an exception
    
  47. Write a function that produces an array of powers of an arbitrary base starting at exponent 0 and going up to some limit. Throw an exception if the base is less than or equal to 1.
        powers(3, 400) ⇒ [1,3,9,27,81,243]
        powers(-2, 17) ⇒ throws an exception
        powers(3, -9) ⇒ []
        powers(0.5, 22) ⇒ throws an exception
    
  48. Write a function that interleaves two arrays. If the arrays do not have the same length, the elements of the longer array should end up at the end of the result array.
        interleave(["a", "b"], [1, 2, true, nil]) ⇒ ["a", 1, "b", 2, true, nil]
        interleave(["a", "b"], []) ⇒ ["a", "b"]
    
  49. Write a function that takes in an array of arrays and returns whether or not the argument is a square matrix. A square matrix is an array with n elements, each of which is an n-element array.
  50. Suppose we have a bunch of objects representing people. Each object has three properties (at least): name, mother, and father. The value of the name property is a string, and the values of the mother and father properties are either other people objects, or are null. Write a function that takes in a person object and returns the array of all of the person's (known) grandparents. Hint: the resulting array will have either 0, 1, 2, 3, or 4 values.
  51. Write a function that takes in two people objects (defined in the previous problem) and returns whether or not they are (known for sure to be) first cousins.
  52. Write a function that takes in a string and produces an object as follows. The string is made up of a number of "pairs" separated by "|" characters. Each pair has its two components separated internally with commas. You need to create a real JavaScript object from the string by treating each pair as a property name together with its value. If that was hard to understand, just "figure it out" from the following examples:
        objectify("a,dog|b,cat|z,rat") ⇒ {a: "dog", b: "cat", z: "rat"}
        objectify("") ⇒ {}
        objectify("one,uno|two,dos") ⇒ {one: "uno", two: "dos"}
    
  53. Suppose you were asked to write a function to take in an array and swap the first and second elements of the array (that's right: actually change the array that was passed in!). You could write:
    var swapFirstTwoElementsOf = function (a) {
        var oldFirstElement = a[0];
        a[0] = a[1];
        a[1] = oldFirstElement;
    }
    
    This works. Then your friend comes along and says "oh hang on, I can do better" and writes this:
    var swapFirstTwoElementsOf = function (a) {
        a = [a[1],a[0]].concat(a.slice(2, a.length));
    }
    
    Does your friend's function work? Why or why not? Be very specific. Use precise, technical language.
  54. Write a script (using Canvas) that draws 20 randomly placed squares, each 30 pixels wide. Make sure each square fits completely in the canvas. The squares can be any color you choose, with any degree of transparency you choose.
  55. What does the following script alert? Why? Illustrate your answer with pictures!
    var x = 2;
    var f = function () {return this.x - 5;}
    var p = {x: 1, y: x, z: f};
    alert(f === p.z);
    alert(f());
    alert(p.z());
    alert(p.y);
    
  56. Write a JavaScript function called take which takes an array a and a number n and returns a new array consisting of the first n elements of a. If n is greater than the length of a, return a copy of a.
  57. Write a JavaScript function called drop which takes an array a and a number n and returns a new array consisting of all but the first n elements of a. If n is greater than the length of a, return an empty array.
  58. Write a function that returns the first value in an array that meets a given condition. By "first" we mean "counting from the left." By "condition" we mean "a function returning a Boolean." For example:
        first([4,3,9,2,10], function (x) {return x > 5}) ⇒ 9
        first([Infinity, "dog", 8, NaN], isFinite) ⇒ 8