You are on page 1of 4

Javascript If Statements

This lesson will teach you the basics of using an "If Statement" in JavaScript. As your JavaScript programs get more sophisticated, you will need to make use of conditional statements that allow your program to make decisions. The "If Statement" is a way to make decisions based on a variable or some other type of data. Examples You might have a variable that stores the date, program a small script to print out, "Today is my Birthday!" whenever the day and month were equal to your birthday Program a small script to print out, Good Morning/Afternoon/Evening

There are two major parts to an If Statement: the conditional statement and the code to be executed. The conditional statement is a statement that will evaluate to be either True or False. The most common type of conditional statement used checks to see if something equals a value. Assignment Operators = Assignment

+= (Adds to the variable that has been assigned, also -=, *=, /=) var jessica = 25; jessica +=25; == != < > <= True or equal to False or not equal to Less than Greater Less than or equal to

Exercise 1
<script type="text/javascript"> var num1 = 10; var num2 = 20;

if(num1<num2) { document.write("Yay it Worked!); } </script>

if/else if Statement
Exercise 2
<script type="text/javascript">

var num1 = 10; var num2 = 20;

if(num1<num2) { document.write("Yay it Worked!); }

else { document.write(It didnt work.); } </script>

Exercise 3
<script type="text/javascript">

var name = Jessica;

if(name == Jessica) { alert("Hey Jess!); } else if (name == Mary)

{ alert("Hello Mary!); } else

{ alert("Who are you?); }

</script>

Exercise 4
<script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 12) { document.write("Good morning!"); } else if (time>=12 && time<18) { document.write("Good afternoon!"); } else { document.write("Good Evening!"); } </script>