JavaScript Cheet Sheet

1.3 Conditional Statements

// Declare variable 'num', Math.random()*10 will pick a random number max 10, Math.random() will round the random number to nearest whole number
var num = Math.round(Math.random() * 10);

// Prompt the user to enter a number and store it in variable 'num'
var guess = prompt("Enter a number between 1 and 10");

// Conditional statements, if num == guess, the first alert is executed
if(num == guess) {
   alert("You Guessed the right number!");

// Next branch of code will execute if 'guess' is less than 1 or (||) greater than 10
} else if (guess < 1 || guess > 10) {
   alert("You did not pick a number between 1 and 10");

// Final branch of code, else, will execute for anything else
} else {
   alert("Sorry, you guess wrong. The number was " +num);
}
// Ask for user input as integer. Switch statement checks the input and displays targeted output or a default output if the input does not match any of the switch cases.

var day = prompt("Please enter the weekday using a" +"number (Mon - 1, Tues - 2, +Wed - 3, Thurs - 4, Fri - 5, Sat - 6, Sun - 7");

switch(day) {
case '1': alert( "Today is Monday" ); break;
case '2': alert( "Today is Tuesday" ); break;
case '3': alert( "Today is Wednesday" ); break;
case '4': alert( "Today is Thursday" ); break;
case '5': alert( "Today is Friday" ); break;
case '6': alert( "Today is Saturday" ); break;
case '7': alert( "Today is Sunday" ); break;
default: alert("Sorry, you did not enter a proper weekday number.");

}