Lecture 9   Class Activities Conditionals

Today

  • Brief recap of JS so far.
  • Booleans and conditionals

Quiz Question Nr. 1

What does the following statement do?

x = y;
  1. It gets an error

  2. It tests whether the two variables are equal

  3. It copies the value of y into x

  4. It copies the value of x into y

Getting Data

In this course, variables will almost always get their values from

  1. other variables and expressions
  2. a user input function like prompt (mostly for testing)
  3. a form. We'll learn how to do forms a bit later.

Quiz Question Nr. 2

We want some code that will ask the user their name and greet them. Which of the following does that?

  1. var user = alert("what's your name?");
    prompt("Greetings, "+user);
    
  2. var user = prompt("what's your name?");
    alert("Greetings, "+user);
    
  3. var user = prompt("what's your name?");
    var greet = "Greetings, "+user;
    alert(greet);
    
  4. var user = alert("what's your name?");
    var greet = "Greetings, "+user;
    prompt(greet);
    

There's a pattern to that kind of code:

  1. Get some input
  2. process it, deriving some result
  3. report the result

Not all of our code will show that pattern, but it often will, so it's worth stepping back to see the pattern.

Booleans and Conditionals

  • Booleans are values that are either true or false
  • Booleans are rarely typed in. They usually come about from tests and comparisons. For example age ≥ 18
  • Conditionals (if statements) can use booleans to decide whether to execute chunks of code or which of two blocks to execute.
  • For example, whether to execute some code:
    if( age ≥ 18 ) {
       alert("Don't forget to vote!");
    }
    
  • For example, choosing which of two block to execute:
    if( cash < 12 ) {
       alert("I'll have pizza");
    } else {
       alert("I'll have the filet mignon, please.");
    }
    
  • Anything can be in the blocks of code of a conditional, including calculations, prompts and other conditionals. Notice how helpful the indentation is!
    if( people_in_party > 1 ) {
        if( cash < 12 ) {
           alert("let's have pizza; my treat!");
        } else {
           alert("filet mignon is on me!");
        }
    } else {
        alert("I'll just have the pizza and eat it alone....");
    }
    
  • This may seem easy so far, but it'll get complicated quickly.

Diagrams for Conditionals

There are some conventional diagrams to help understand conditionals; these are known as flowcharts.

if-then statement
The first form allows you to optionally skip a code block
if-else statement
The second form allows you to choose one of two mutually exclusive code blocks

Quiz Question Nr. 3

Suppose a variable called hour contains the hour of the day, using a 24-hour clock (0--23). What is the best way to greet someone?

  1.     if hour < 12 {
            alert("Good morning!");
        } else {
            alert("Good afternoon!");
        }
    
  2.     if( hour < 12 ) {
            alert("Good afternoon!");
        } else {
            alert("Good morning!");
        }
    
  3.     if( hour < 12 ) {
            alert("Good morning!");
        }
        if( hour > 12 ) {
            alert("Good afternoon!");
        }
    
  4.     if( hour < 12 ) {
            alert("Good morning!");
        } else {
            alert("Good afternoon!");
        }
    

Note: A common beginner error is to test for both something and its opposite. For example, testing if a number is odd and then testing if it's even. Better is to test if it's odd, and if it's not, you know it's even, so you can just use the else keyword.

Quiz Question Nr. 4

Suppose you've just used the prompt() function to ask the user for their name, and the value is stored in a variable called username. You want to see if they typed anything and complain if they didn't. Which of the following would complain appropriately? (The value "" refers to an empty string.)

  1.    if( username = "" ) {
           alert("please type your name");
       }
    
  2.    if( username.length < 1 ) {
           alert("please type your name");
       }                      
    
  3.    if( username.length == "" ) {
           alert("please type your name");
       }
    
  4.    if( username == "" ) {
           alert("please type your name");
       }
    

Note:

  • Be really careful when you use equality tests; it's so easy to confuse = with ==.
  • The boolean expression in the parentheses is either true or false.
  • It's equivalent to compare to the empty string and to check that the length is zero. Those are the same.
  • It's optional to surround a single statement with braces, but we recommend it.

Quiz Question Nr. 5

What is the result of the following code? Note that you are allowed encouraged to use the JS console to find out!

var y = Math.floor(3.8);
  1. 3.8

  2. 4

  3. 3.5

  4. 3

Quiz Question Nr. 6

What is the value of y as a result of the following code? Again, you are allowed encouraged to use the JS console to find out! We'll discuss this syntax (called a method a bit later in the course).

var x = 13;
var y = x.toString(16);
  1. 13

  2. 3

  3. a

  4. d

Wellesley Class Year

Write some JS code that does the following:

  1. prompt the user to enter the year she enrolled at Wellesley, capturing the string of digits in a variable. You get to name the variable.
  2. use the parseInt function to convert the string of digits into a number that we can do arithmetic with. Put the result in a new variable. You get to name this variable, too.
  3. report back to the user using alert whether she is a current student, an alum, or a future student.

Hex Conversions in JavaScript

We can use JavaScript to convert decimal values to hex values. This will give us some opportunities to use conditionals.

Write some JS code to does the following:

  1. prompt the user for a decimal number, capturing the string of digits in a variable. You get to name the variable.
  2. use the parseInt function to convert the string of digits into a number that we can do arithmetic with. Put the result in a new variable. You get to name this variable, too.
  3. Use the remainder operator, %, to compute the units digit of the hex conversion. Put the result in a new variable.
  4. Report the result using alert.
  5. Copy your code to jsfiddle.net, so that you can easily re-run it by clicking the "run" button.
  6. Test your code

Hex Conversions with Conditionals

Once you've got that working, add a conditional to report whether the units digit will be a numeral (0-9) or a letter (A-F). Test it with your jsfiddle.

Hex with More Conditionals

Add another conditional to report whether the hex string will be one digit or more than one digit. Can you think of how to do this? Test it with your jsfiddle.

Hex Conversions with 16s Place

  1. Add code to compute the value of the 16s place.
  2. create the hex string for the conversion.

After each step, test it with your jsfiddle.

Conditionals with Fall Colors

We've implemented a function on this page, just for fun:

  • fallColors() changes the colors of the page to a garish display of fall colors

Implement some JavaScript code that prompts the user for their favorite season. If they answer "fall", invoke the fallColors() function. Note that you won't be able to test this using jsfiddle (because jsfiddle lacks the magic functions), but you can test it in your JS console. The point of this is to do a conditional using a string.

You might come up with something like this:

    var season = prompt("What's your favorite season?");
    if( season == "fall" ) {
        fallColors();
    }
  

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Thursday, 09-Mar-2017 10:55:51 EST

Solutions

Will be posted later, visit again after .

Quiz answers:

        1. C ; it copies into x, the left-hand side
        2. B or C; either will work
        3. D is best.  C will also work but it's not as good
        4. B or D will work. D is most common.
        5. D ; Math.floor() computes the integer below the number
        6. D ; .toString(16) converts to base 16.
      

Wellesley Class Year

            var input=prompt("In what year did you enroll at Wellesley College?");
            var year=parseInt(input);
            if (year>2017){
                alert ("Welcome future Wellesley Student!")
            }
            else if (year >=2013){
                alert ("You are a current student.")
            }
                else {
                    alert ("Welcome back alumna!")
                }
        

Hex Conversions in JavaScript:

            var entered = prompt("Please enter a decimal number");
            var num = parseInt(entered);
            var units = num % 16;
            alert("The units digit is "+units);
          

Hex Conversions with Conditionals:

            var entered = prompt("Please enter a decimal number");
            var num = parseInt(entered);
            var units = num % 16;
            alert("The units digit is "+units);
            if( units > 9 ) {
                alert("digit will be a letter");
            } else {
                alert("digit will be a numeral");
            }
          

Hex with More Conditionals:

            var entered = prompt("Please enter a decimal number");
            var num = parseInt(entered);
            var units = num % 16;
            alert("The units digit is "+units);
            if( units > 9 ) {
                alert("digit will be a letter");
            } else {
                alert("digit will be a numeral");
            }
            if( num >= 16 ) {
                alert("result will be multiple digits");
            }
          

Hex Conversions with 16s Place:

            var entered = prompt("Please enter a decimal number");
            var num = parseInt(entered);
            var units = num % 16;
            var sixteens = Math.floor(num/16);
            alert("The sixteens digit is "+sixteens);
            alert("The units digit is "+units);
            var hex = sixteens.toString(16) + units.toString(16);
            alert("the hex conversion is "+hex);