Introduction to (Web) Programming

Lab 1


Goals


Instructions


Programming with Blocks


JavaScript basics

  1. A warm up. Using the browser’s JavaScript console, try these examples in order, one at a time:

      > 33 + 47
    
      > x
    
      > let x = 5;
    
      > x
    
      > x = x + 1;
    
      > x
    
      > alert('x');
    
      > alert(x);
    
      > alert('the value of x is ' + x);
  2. String exercises. Try these in order (again, using the browser’s JavaScript console), one at a time:

      > let word = 'the';
    
      > word.length
    
      > alert(word);
    
      > let phrase = word + ' time';
    
      > alert(phrase);
    
      > phrase = 'now is ' + phrase;
    
      > alert(phrase);
    
      > phrase.length
  3. Inputting numbers. Again, using the browser’s JavaScript console, try the three examples below, one at a time:

      > prompt('type something: ')             // type 34
    
      > parseInt(prompt('type something: '))   // type 34
    
      > parseInt(prompt('type something: '))   // type thirty-four

    You should be able to explain why the result produced is different in each case.

  4. Experiment more with the JavaScript console. Identify cases where the console’s response is not what you would expect.


    For the remaining problems, download lab1.html and work within the script tags near the top of the file. Test your code by opening your the file in your browser and clicking on the corresponding buttons. You can compare your results to the demo solution.

  5. Inches per mile. Complete the function milesToInches so that it asks the user to enter a number of miles, computes the equivalent number of inches in that number of miles and displays that in an alert box. For example, If the user enters 6 in the prompt box, it should produce a dialog (alert) box that says

        There are 380160 inches in 6 miles.

    (Hint: there are 12 inches in a foot and 5280 feet in a mile.)

  6. An algorithm’s inverse. Below is a program that converts Celsius to Fahrenheit:

    function c2f() {
        let c = parseInt(prompt('What is the Celsius temperature?'));
        let f = (9.0/5.0) * c + 32;
        alert(c + ' degrees Celsius is ' + f + ' degrees Fahrenheit.');
    }

    Write a similarly structured function f2c that achieves the inverse: converts Fahrenheit to Celsius.

  7. Hours, minutes, seconds [courtesy of Jim Marshall]. Write a function seconds that asks the user for a total number of seconds, and converts this to the corresponding number of hours, minutes, and seconds. (Hint: the remainder operator % might come in handy here.) Examples: If the user enters 250 seconds, the program (i.e., clicking on the second button) should output (i.e., display using an alert box):

        That is 0 hours 4 minutes and 10 seconds.

    If the user enters 10000 seconds, the program should output:

        That is 2 hours 46 minutes and 40 seconds.