Quiz

  1. I'm a little confused on how to connecting an external JS file works in html:
        <script type=""text/javascript"" src=""helloWorld.js""></script>
    
    For different actions would you need multiple javascript files? Or if actions are located in different places in an HTML file do you have to reference the same javascript multiple times?

    This is a great question and a very deep one, which we will dig into in a later reading. It has to do with issues like namespaces and modules. (Python has these as well, but I don't think that's covered much in CS111.)

    There are two kinds of files (modules) in JS:

    • The original files are all in the same namespace: a bucket of names for things like functions and variables. So if file A defines a function foo, then file B can call foo.

      Think about how jQuery defines the function jQuery (and its synonym, $), and we can use it in our script elements. It's all one big namespace.

    • In the modern module system, you can define each file as a separate namespace, so file A can define a function tan (maybe the color) and file B can define its own function tan (maybe the tangent function), and they are entirely separate. Then there are mechanisms to export names to other modules and import names from other modules.

    For now, we'll use the original version, and we'll learn the module system later.

  2. I am still a little confused about the purpose of using anonymous functions. Just to make sure I am understanding it right, you can only refer to anonymous functions by storing it in a variable?

    Correct: if you want to refer to it later, you'd have to store it somewhere (in a variable, or in an array or an dictionary or someplace...)

    However, that's not really the purpose. The purpose is when you don't want to refer to it later. You only need it once, so why not just state the code directly.

    Here's an analogy. Suppose we are given the side length of a square and we need to compute the perimeter. Which code to you prefer:

    
        // using a literal constant:
        const perimeter = 4 * side;
    
        // or using a named constant:
        const squarePerimeterRatio = 4;
        const perimeter = squarePerimeterRatio * side;
    
    

    Honestly, there's a case to be made for the latter, but most people would code the former. You can think of the first one as using an anonymous constant.

    But the case for anonymous functions is even stronger. Suppose you need to raise prices by P percent for a bunch of items stored in a list. Which of the following do you prefer:

    
    // using a function in a variable:a
    const percentMore = (x) => (1+p)*x;
    const raisedPrices = prices.map(percentMore);
    
    // Or using a function literal
    const raisedPrices = prices.map((x) => (1+p)*x);
    
    
    Since the code of the anonymous function is simple and clear, the code itself is a sufficient explanation of what the function is doing. There's no need to name the function.

    This kind of coding is done a lot in web development.

  3. Can you please go over .map and .forEach and the differences between var, const, and let in class? Thank you! Great reading, the topics were really well explained.

    I'm glad you found the explanations to be good!

    We just saw an example of .map: it's like a Python list comprehension, except that you have to package up the code in a function, which can be anonymous.

    the forEach method is similar except it doesn't create a new list of return values, so it's more like a loop.

    
        let totalPrice = 0;
        prices.forEach( x => totalPrice += x );
        console.log('total is ', totalPrice);
    
    

    Now, the differences between var, let and const.

    The first two are the same for our purposes. As I said in the reading, there are subtle differences between var and let, but those subtleties have never arisen in CS 204. If you really care (and it would be okay to care — maybe you're taking CS 251 Programming Languages), I'd be happy to talk with you in office hours.

    The keyword const is different because you are telling the computer that you will never re-assign that value:

    
        const n = 3;
        n = n + 1;     // illegal, you promised that this is an error
        // the following loop variable is illegal as well:
        for( const i = 0; i < 10; i++ ) {  ... }
    
    

    Note that this does not say that the value is immutable:

    
        const students = [];
        students.push("Alice");   // perfectly legal
        students.pop();           // also legal
        students = ["Betty"];     // error: re-assignment not allowed
    
    
  4. This is a clarification question: You mentioned that JavaScript functions use the keyword function, but the example uses
        def: def process(x) { return Math.sqrt(x); }.... 
    
    Is this example actually JavaScript, or is it an exception?

    D'oh! You caught me! That's a mistake (one which several years of students hadn't caught, so bravo to you). I meant to say function. I've fixed the reading.

  5. What's the hardest adjustment you have to make from python to javascript?

    Making mistakes like the one above. That and a moment's hesitation when I type, say, if and then I have to think: parens around an expression? an expression ending in a colon?

    But these are all pretty minor. You get better at it, and you shouldn't worry about when it happens.

  6. can you give another example of how to sort in javascript?

    We've sorted numbers and strings, and those are all the basic datatypes we know so far. When we learn dictionaries, we'll learn how to sort those.

    Hmm. Here's one. Suppose we have a list of numbers both positive and negative, and we want to sort them by their magnitude.

    
        var nums = [ 1, -2, 3, -4, 5, -6 ];
        nums.sort((a,b) => a-b);
        console.log(nums);
        nums.sort((a,b) => Math.abs(a)-Math.abs(b));
        console.log(nums);
    
    
    
  7. Could you please explain words.sort(cmp) in the sort function? I dont understand how it works with only two parameters and multiple items inside an array. How does it iterate? Thank you.

    Ah, I discussed sorting right after discussing mapping, because they are similar in having a function argument, but they are different algorithms.

    the mapping methods process items one at a time, left to right (usually), so the function only takes one argument.

    But sorting is a more complex algorithm that compares pairs of items, and shuffles items around based on those comparisons. So the function takes two arguments. Those arguments will be list items, but not necessarily even consecutive list items.

    Don't get me started on sorting algorithms. They're too much fun. You'll learn about them in CS 230.

  8. Why do we need to convert the input variables strings into upper case first in a comparison function? Can we instead convert them into lower case?

    Sure, that would also work.

  9. Are JavaScript Objects similar to Java Objects?

    Yes, they are similar. But not exactly the same. We'll talk about them several times this semester.